[英]What method does Python call when I access an attribute of a class via the class name?
I know accessing the attributes of Foo through an instance will call the __getattribute__()
method, but what if I access this attribute directly through the class ?我知道通过实例访问 Foo 的属性将调用
__getattribute__()
方法,但是如果我直接通过 class 访问此属性会怎样? If a function is called, I want to set a breakpoint in it so that the breakpoint can be triggered when accessing this property through a class in my project.如果调用了一个function,我想在其中设置一个断点,这样在我的项目中通过一个class访问这个属性时可以触发断点。
I have tried to set breakpoint in magic method __getattribute__()
, but nothing hapened.我试图在魔术方法
__getattribute__()
中设置断点,但没有任何反应。
class Foo:
age = 18
print(Foo.age) # I am curious what method is called
Everything in Python is an object and everything has a type
that determines the object's behavior. Python 中的所有内容都是 object,并且所有内容都有一个确定对象行为的
type
。 This also holds for class objects.这也适用于 class 个对象。 You can check
type(Foo)
:您可以检查
type(Foo)
:
>>> type(Foo)
<class 'type'>
You can customize the type of a class by providing a custom metaclass
.您可以通过提供自定义
metaclass
来自定义 class 的类型。 This metaclass is then responsible for attribute access on the class object:然后这个元类负责对 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)
and the output is: output 是:
__getattribute__(<class '__main__.Foo'>, 'age')
18
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.