Home > database >  Inheritance: why does self refer to child class?
Inheritance: why does self refer to child class?

Time:06-10

Sorry I could not come up with a better title.

Please consider this example:

class A:
    def __init__(self, x):
        self.attr = x

class B(A):
    x = 1

    def __init__(self):
        super().__init__(x=self.x)

class C(B):
    x = 2

    def __init__(self):
        super().__init__()


c = C()
print(c.attr) # 2

This code prints 2.

This means self in B.__init__ is an instance of C, not B.

I thought that the purpose of super was to refer to the methods/attributes of the parent class. Can somebody please explain the logic behind the output not being 1? Thank you.

CodePudding user response:

The purpose of super() in super().__init__() is to call the __init__() method from the parent. It doesn't change the object itself -- it's still an instance of the subclass. So anything that the subclass overrides will be visible in the instance.

If the parent method doesn't want the overridden value of x, it should use B.x rather than self.x. The whole point of accessing the attribute through self is to take advantage of overriding in subclasses.

  • Related