魔法方法__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__('韩晓萌')
...
else: ... raise AttributeError('没有属性%s!' % attr) ... >>> p = Person('韩晓萌') >>> p.name '韩晓萌' >>> p.age Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 8, in __getattribute__ 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('韩晓萌')
>>> 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

猜你喜欢

转载自www.cnblogs.com/hanxiaomeng/p/12711696.html