What happens exactly when a python class instance use dot to access attributes?

142 Views Asked by At

Suppose a class A is defined as:

class A:
    def __init__(self, val):
        self.val = val

After A is instantiated by a = A(3), what methods will be called by executing a.val? In other words, what will happen internally when a.val is executed?

Moreover, how about A accessing a non-existed attribute, namely other_val, by executing A.other_val?

I heard about built-in methods such as getattr and setattr, and class protocol method __getattr__, __setattr__ and __getattribute__, which of them and how they are triggered when A.* is executed?

I only found few documentations on this, so any materials that explains the problem will help. Thanks in advance.

1

There are 1 best solutions below

1
SIGHUP On

When you [try to] access a class instance attribute using dot notation, the class's __getattribute__ method will be invoked. This can be demonstrated thus:

class A():
    def __init__(self):
        self.val = 99
    def __getattribute__(self, attr):
        print(f'Acquiring {attr}')
        return super(type(self), self).__getattribute__(attr)


a = A()

print(a.val)

Output:

Acquiring val
99