【问题标题】:How does __setattr__ and __getattribute__ interact in Python?__setattr__ 和 __getattribute__ 在 Python 中如何交互?
【发布时间】:2021-05-08 22:11:05
【问题描述】:
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)

从上面的代码结果是:

Initializing setattr
Initializing getattribute
Initializing getattribute
6

我知道每个 dunder 方法在哪里被调用,但它们真正做了什么?在前面的示例中,getattribute 指示属性值以及如果我删除该行:

return object.__setattr__(self,attribute,value)

没有任何变化。

那么__setattr__ 做了什么?

【问题讨论】:

标签: python class methods


【解决方案1】:

__getattribute__ 在任何其他尝试访问属性之前被调用。不管__setattr__做什么,test.age都是由test.__getattribute__("age")处理的,不管有没有名为age的属性,它都会返回6

如果你摆脱__getattribute__

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)

该类行为正常,将test.age 设置为4。如果您进一步摆脱对object.__setattr__ 的调用,那么您将获得AttributeError,因为self.age = age 永远不会实际创建或设置@987654333 @ 属性;它只是打印初始化消息并返回:

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)

结果

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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    相关资源
    最近更新 更多