Super class has attribute "b", still got "AttributeError: 'super' object has no attribute 'b' "

138 Views Asked by At

super class has instance attribute b, I am trying to access it using super() method, then why I am getting Attribute Error? It should access instance variable of superclass, but instead it is giving attribute error, anyone please tell where I am wrong.

Here superclass is defined P

Child class C inherits class P

class P:
    a = 10
    def __init__(self):
        self.b = 20

class C(P):
    a = 888
    def __init__(self):
        self.b = 999
        super().__init__()
        print(super().a)
        print(super().b)

c = C()

Output

PS D:\python_practice> python .\test.py
10
Traceback (most recent call last):
  File ".\test.py", line 21, in <module>
    c = C()
  File ".\test.py", line 19, in __init__
    print(super().b)
AttributeError: 'super' object has no attribute 'b'
1

There are 1 best solutions below

0
ShadowRanger On

super() is for finding attributes (usually methods, but as you can see, it works on class attributes as well) on a later class in the class method resolution order (MRO). Instance attributes aren't tied to a particular class in the hierarchy (they're all stored on the instance itself, typically in a single dict under the hood), you just look them up on self directly.

In this case, there is only one b attribute, and it's whatever was assigned last. Since you invoked super().__init__() after assigning to self.b in the child class, the parent class is replacing self.b, so self.b = 999 is meaningless; instances of both parent and child will only have self.b with value 20 after initialization completes.

super() could be useful to find a class attribute on a superclass that has been shadowed by an instance attribute, but if both class and superclass used the same instance attribute name (and private name mangling is not involved) it's the same attribute shared by both, there is no distinction between the version used at different levels in the hierarchy.