如何在Python函数中找到属性?

时间:2014-08-13 20:35:28

标签: python inheritance attributes

我一直在玩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吗?

1 个答案:

答案 0 :(得分:2)

Special methods are looked for in the class of the object,不在实例的属性中。因此,为了影响foo.a,您需要修改__getattribute__的{​​{1}}方法type(foo)。但是,内置类型function不允许您更改其function方法:

__getattribute__

我认为在C中定义的所有对象都是如此,而不是Python。