0

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.

  • Which documentation have you found so far? – CoffeeTableEspresso Oct 27 '22 at 14:01
  • https://docs.python.org/3/reference/datamodel.html#special-method-names gives a pretty good overview of what each of these special methods does – CoffeeTableEspresso Oct 27 '22 at 14:04
  • @CoffeeTableEspresso Thanks for your link and I even failed to find this official documentation. This official document looks quite useful to my problems and I will delve into it. Feedbacks will be commented later. – Orange Chen Oct 27 '22 at 14:25

1 Answers1

1

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
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • Thanks for your answer and it helps. I wanna go deeper into the invoking process. Does `A.*` immediately invoke `__getattribute__` or immediately invoke some other methods that further invoke `__getattribute__`? – Orange Chen Oct 27 '22 at 14:37