[英]python: What happens when class attribute, instance attribute, and method all have the same name?
[英]What method does Python call when I access an attribute of a class via the class name?
我知道通过实例访问 Foo 的属性将调用__getattribute__()
方法,但是如果我直接通过 class 访问此属性会怎样? 如果调用了一个function,我想在其中设置一个断点,这样在我的项目中通过一个class访问这个属性时可以触发断点。
我试图在魔术方法__getattribute__()
中设置断点,但没有任何反应。
class Foo:
age = 18
print(Foo.age) # I am curious what method is called
Python 中的所有内容都是 object,并且所有内容都有一个确定对象行为的type
。 这也适用于 class 个对象。 您可以检查type(Foo)
:
>>> type(Foo)
<class 'type'>
您可以通过提供自定义metaclass
来自定义 class 的类型。 然后这个元类负责对 class object 的属性访问:
class MyMeta(type):
def __getattribute__(self, name):
print(f'__getattribute__({self!r}, {name!r})')
return super().__getattribute__(name)
class Foo(metaclass=MyMeta):
age = 18
print(Foo.age)
output 是:
__getattribute__(<class '__main__.Foo'>, 'age')
18
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.