我一直在玩Python的魔术方法,我遇到了一个有趣的行为:
In [1]: def foo(x):
...: return x
...:
In [3]: foo.a = 10
In [4]: foo.func_dict
Out[4]: {'a': 10}
In [6]: def getter(*x):
return 5
...:
In [7]: foo.__getattribute__ = getter
In [8]: foo.a
Out[8]: 10
In [9]: foo.func_dict
Out[9]: {'__getattribute__': <function __main__.getter>, 'a': 10}
由于我覆盖了foo __getattribute__
,我不应该foo.a
返回5
吗?
答案 0 :(得分:2)
Special methods are looked for in the class of the object,不在实例的属性中。因此,为了影响foo.a
,您需要修改__getattribute__
的{{1}}方法type(foo)
。但是,内置类型function
不允许您更改其function
方法:
__getattribute__
我认为在C中定义的所有对象都是如此,而不是Python。