1

I was experimenting with class inheritance using the code below:

>>> class Class1:
        clsattr1 = 1
        def __init__(self):
            self.selfattr1 = 1

        
>>> class Class2:
        clsattr2 = 2
        def __init__(self):
            self.selfattr2 = 2

        
>>> class ClassA(Class1, Class2):
        def __init__(self):
            super(Class1, self).__init__()
            super(Class2, self).__init__()

        
>>> classa = ClassA()
>>> classa.clsattr1, classa.clsattr2
(1, 2)
>>> classa.selfattr1
Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    classa.selfattr1
AttributeError: 'ClassA' object has no attribute 'selfattr1'
>>> classa.selfattr2
2
>>> classa.__dict__
{'selfattr2': 2}

As you can tell, the child class (ClassA) did not inherit the instance attributes of Class1, the first parent class (the selfattr1 attribute). What is the explanation for this behavior? Also, should I change my code so that ClassA inherits the instance attributes of both Class1 and Class2 (preferably using super(), or something similar)?

martineau
  • 119,623
  • 25
  • 170
  • 301
Jacob Lee
  • 4,405
  • 2
  • 16
  • 37
  • 1
    This is **not** how `super` works. You are using it incorrectly. You should just use `Class1.__init__(self); Class2.__init__(self)`. You fundamentally misunderstand `super`, which is to provide the *next* class in the method-resolution order. You aren't supposed to pass *other* classes to super within a class, always the class itself. Important reading: https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ also, a video: https://www.youtube.com/watch?v=EiOglTERPEo – juanpa.arrivillaga Apr 17 '21 at 22:10

0 Answers0