zoukankan      html  css  js  c++  java
  • Python魔法方法__getattr__、__setattr__、__getattribute__的介绍

    一、__getarribute__方法

    __getattribute__(self, name):拦截所有的属性访问操作

    >>> class Person:
    ...     def __init__(self, name):
    ...             self.name = name
    ...     def __getattribute__(self, attr):
    ...             if attr == 'name':
    ...                     return '姓名:' + super().__getattribute__(attr)
    ...             else:
    ...                     return raise AttributeError('属性%s不存在!' % attr)
    ...
    >>> p = Person('韩晓萌')
    >>> p.name
    '姓名:韩晓萌'
    >>> p.age
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 属性age不存在!

    二、__getattr__方法

    __getattr__(self, name):拦截对不存在属性的访问操作

    >>> class Person:
    ...     def __init__(self, name):
    ...             self.name = name
    ...     def __getattr__(self, attr):
    ...             raise AttributeError('没有属性%s!' % attr)
    ...
    >>> p = Person('韩晓萌')
    >>> p.name
    '韩晓萌'
    >>> p.age
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 5, in __getattr__
    AttributeError: 没有属性age!

    三、__setattr__方法

    __setattr__(self, attr, value):拦截所有属性的赋值操作

    >>> class Person:
    ...     def __init__(self, name):
    ...             self.name = name
    ...     def __setattr__(self, attr, value):
    ...             if attr == 'name':
    ...                     if not isinstance(value, str):
    ...                             raise TypeError('name的值必须是字符串!')
    ...                     self.__dict__[attr] = value
    ...             else:
    ...                     super().__setattr__(attr, value)
    
    >>> p = Person(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in __init__
      File "<stdin>", line 7, in __setattr__
    TypeError: name的值必须是字符串!
    >>> p = Person('韩晓萌')
    >>> p.name
    '韩晓萌'
    >>> p.name = 1
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 7, in __setattr__
    TypeError: name的值必须是字符串!
    >>> p.name = '杨超越'
    >>> p.name
    '杨超越'
    >>> p.age = 21
    >>> p.age
    21
  • 相关阅读:
    BZOJ3631: [JLOI2014]松鼠的新家
    网络流24题题目总会+题解
    BZOJ3930: [CQOI2015]选数
    BZOJ4816: [Sdoi2017]数字表格
    Launcher类源码分析
    平台特定的启动类加载器深入分析与自定义系统类加载器详解
    类加载器命名空间总结与扩展类加载器要点分析
    类加载器命名空间深度解析与实例分析
    类加载器实战剖析与疑难点解析
    类加载器命名空间实战剖析与透彻理解
  • 原文地址:https://www.cnblogs.com/hanxiaomeng/p/12711696.html
Copyright © 2011-2022 走看看