在Python中,setattr和getattribute是如何交互的?
根据上面的代码,结果是:在Python中,setattr和getattribute是如何交互的?,python,class,methods,Python,Class,Methods,根据上面的代码,结果是: class Test(): def __init__(self,age): self.age=age def __getattribute__(self,attribute): print("Initializing getattribute") return 6 def __setattr__(self,attribute,value): print("
class Test():
def __init__(self,age):
self.age=age
def __getattribute__(self,attribute):
print("Initializing getattribute")
return 6
def __setattr__(self,attribute,value):
print("Initializing setattr")
return object.__setattr__(self,attribute,value)
test=Test(4)
test.age
print(test.age)
我了解每个dunder方法的调用位置,但它们真正做什么?在前面的示例中,getattribute指定属性值,如果我删除该行:
返回对象。\uuuu setattr\uuuuuu(self,attribute,value)
没有什么变化
那么
\uuuuu setattr\uuuuu
做什么呢?\uuuuu getattribute\uuuuu
在尝试访问属性之前被调用。无论\uuuu setattr\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
如果您摆脱了\uuuu getattribute\uuuu
:
Initializing setattr
Initializing getattribute
Initializing getattribute
6
该类行为正常,将test.age
设置为4。如果您进一步取消对对象的调用。\uuuu setattr\uuuuu
,那么您将获得AttributeError
,因为self.age=age
永远不会实际创建或设置age
属性;它只打印初始化消息并返回:
class Test():
def __init__(self,age):
self.age=age
def __setattr__(self,attribute,value):
print("Initializing setattr")
return object.__setattr__(self,attribute,value)
test=Test(4)
test.age
print(test.age)
导致
class Test():
def __init__(self,age):
self.age=age
def __setattr__(self,attribute,value):
print("Initializing setattr")
test=Test(4)
test.age
print(test.age)
初始化setattr
回溯(最近一次呼叫最后一次):
文件“/Users/chepner/tmp.py”,第11行,在
测试年龄
AttributeError:“测试”对象没有属性“年龄”
这是否回答了您的问题?
Initializing setattr
Traceback (most recent call last):
File "/Users/chepner/tmp.py", line 11, in <module>
test.age
AttributeError: 'Test' object has no attribute 'age'