__getattr__与__getattribute__
class Foo:
def __init__(self,x):
self.x=x
def __getattr__(self, item):
print('执行getattr')
def __getattribute__(self, item):
print('执行getattribute')
f=Foo(10)
f.x
f.xx
#输出为
#执行getattribute
#执行getattribute
内置方法(一)中说过当属性存在时不会调用__getatrr__,只有属性不存在时才调用__getatrr__
而上面的例子说明无论属性存不存在都会调用__getatrribute__,
但是上面的例子似乎在访问不存在的属性时没有调用__getatrr__,为什么?继续看下面例子
class Foo:
def __init__(self,x):
self.x=x
def __getattr__(self, item):
print('执行getattr')
def __getattribute__(self, item):
print('执行getattribute')
raise AttributeError #注意这行加入的抛出属性错误
f=Foo(10)
f.x
f.xx
#输出为
执行getattribute
执行getattr
执行getattribute
执行getattr
由上面一个例子可以看出,无论属性存不存在,都会调用__getatrribute__,但只有在抛出AttributeError时才会再次调用__getatrr__函数.
__item__
class Foo:
def __init__(self,x):
self.x=x
def __getitem__(self, item):
print('执行getitem')
print(self.__dict__[item])
def __setitem__(self, key, value):
print('执行setitem')
self.__dict__[key]=value
def __delitem__(self, key):
print('执行delitem')
self.__dict__.pop(key)
f=Foo(10)
print(f.__dict__)
f['x']
f['y']=1
print(f.__dict__)
del f['y']
print(f.__dict__)