- 使用
___getattribute__
获取不存在的属性会报异常, - 而
__getattr__
会捕获异常
class Hero():
def __init__(self,name):
self.name = name
def __setattr__(self, key, value):
'''给设置属性时,会调用此方法'''
if key == 'name':
value = '888'
print('---__setattr__--')
object.__setattr__(self, key, value)
def __getattribute__(self, item):
'''查找属性时,会直接调用该方法,进行查找'''
print(f'这个是__getattribute__:item:{item}')
return object.__getattribute__(self,item)
h = Hero('静静')
print(h.name)
print(h.age)
运行结果:
---__setattr__--
Traceback (most recent call last):
这个是__getattribute__:item:name
888
这个是__getattribute__:item:age
File "C:/workspace/pythonTest/pythonDemo/getattr.py", line 25, in <module>
print(h.age)
File "C:/workspace/pythonTest/pythonDemo/getattr.py", line 16, in __getattribute__
return object.__getattribute__(self,item)
AttributeError: 'Hero' object has no attribute 'age'
由运行结果可知由于age属性并不存在,所以此刻会会报出异常:
class Hero():
def __init__(self,name):
self.name = name
def __setattr__(self, key, value):
'''给设置属性时,会调用此方法'''
'''当这个类的属性被访问时,会自动调用类的__getattribute__方法'''
if key == 'name':
value = '888'
print('---__setattr__--')
object.__setattr__(self, key, value)
def __getattribute__(self, item):
'''查找属性时,会直接调用该方法,进行查找'''
print(f'这个是__getattribute__:item:{item}')
return object.__getattribute__(self,item)
def __getattr__(self, item):
'属性不存在,该方法会主动捕获异常'
print(f'这个是__getattr__:item:{item}')
h = Hero('静静')
print(h.name)
print(h.age)
运行结果:
---__setattr__--
这个是__getattribute__:item:name
888
这个是__getattribute__:item:age
这个是__getattr__:item:age
None
由运行结果可知,获取属性会先去调用__getattribute__方法,发现不存在然后再去调用 __getattr__方法;
使用 __getattr__当属性不存在时可以捕获并抛出异常:
class Hero():
def __init__(self,name):
self.name = name
def __setattr__(self, key, value):
'''给设置属性时,会调用此方法'''
if key == 'name':
value = '888'
print('---__setattr__--')
object.__setattr__(self, key, value)
def __getattribute__(self, item):
'''查找属性时,会直接调用该方法,进行查找'''
print(f'这个是__getattribute__:item:{item}')
return object.__getattribute__(self,item)
def __getattr__(self, item):
'属性不存在,该方法会主动捕获异常'
print(f'这个是__getattr__:item:{item}')
if item == 'age':
return 111
raise AttributeError
return object.__getattr__(self, item)
def __delattr__(self, item):
print(f'这个是item:{item}')
if item == 'name':
pass
else:
object.__delattr__(self,item)
h = Hero('静静')
print(h.age)
---__setattr__--
这个是__getattribute__:item:age
这个是__getattr__:item:age
111