class Foo02:
def __getattr__(self, item):
""" 该方法在访问一个不存在的属性时调用 """
print('__getattr__')
if item not in self.__dict__:
return None
return super(Foo02, self).__getattr__(item)
def __setattr__(self, key, value):
""" 该方法在对属性进行赋值和修改时调用,应该避免"无限递归"错误,如: self.name = 'xxx' """
print('__setattr__')
self.__dict__[key] = value
return super(Foo02, self).__setattr__(key, value)
def __delattr__(self, item):
""" 该方法在删除属性时调用 """
print('__delattr__')
return super(Foo02, self).__delattr__(item)
def __getattribute__(self, item):
""" 该方法在属性被访问时调用,调用__getattr__前必定会调用 __getattribute__ """
print('__getattribute__')
return super(Foo02, self).__getattribute__(item)
foo02 = Foo02()
foo02.abc = 'abc'
print(foo02.abc)
print('error---', foo02.x)
foo02.__dict__
del foo02.abc