Reputation: 580
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? 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.
I have tried to set breakpoint in magic method __getattribute__()
, but nothing hapened.
class Foo:
age = 18
print(Foo.age) # I am curious what method is called
Upvotes: 6
Views: 1622
Reputation: 36299
Everything in Python is an object and everything has a type
that determines the object's behavior. This also holds for class objects. You can check type(Foo)
:
>>> type(Foo)
<class 'type'>
You can customize the type of a class by providing a custom metaclass
. This metaclass is then responsible for attribute access on the 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:
__getattribute__(<class '__main__.Foo'>, 'age')
18
Upvotes: 5