Does__getattr__ 允许修改传递的值?

Does__getattr__ allow modifying passed value?

这是我的代码:

class myclass:
    def __init__(self):
        self.value = 5

    def __getattr__(self, attrname):
        if attrname == 'value':
            return 10

X = myclass()
print X.value

我想输出值应该是10__getattr__修改返回值)。但是输出是 5.

如果我删除值的初始化:

class myclass:

    def __getattr__(self, attrname):
        if attrname == 'value':
            return 10

X = myclass()
print X.value

它按预期工作 (returns 10)。 为什么?

__getattr__ 仅用于 缺失的 属性。见 documentation:

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self).

在您的第一个示例中,'value' 不是缺失的属性;它是在 __init__ 中设置的。请注意,设置位置无关紧要,重要的是它存在。

如果必须拦截所有属性访问,则需要实现__getattribute__ hook