0

Let suppose we have defined two classes:

class A():
    def __init__(self):
        self.a = 0

class B():
    def __init__(self):
        self.b = 0

Now, we want to define a third class C that inherits from A and B:

class C(A, B):
    def __init__(self):
        A.__init__(self)   # how to do this using super()
        B.__init__(self)   # how to do this using super()
ThunderPhoenix
  • 1,649
  • 4
  • 20
  • 47
  • FWIW, I've indirectly answered this in [my answer here](https://stackoverflow.com/a/50465583/1222951). (The answer is `super().__init__()` followed by `super(A, self).__init__()`.) – Aran-Fey Nov 25 '19 at 14:14
  • Does this post answer your question ? [super multiple inheritance](https://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance) – Arkenys Nov 25 '19 at 14:16
  • 1
    Plus see rhettinger's [super considered super](http://rhettinger.wordpress.com/2011/05/26/super-considered-super). which he links to from his own answer to that question. – Daniel Roseman Nov 25 '19 at 14:17
  • Have you tried looking for an answer anywhere before asking? https://stackoverflow.com/a/27134600/4744341 – natka_m Nov 25 '19 at 14:18

1 Answers1

1

You did not specify whether you are Python 2 or Python 3 and it matters as we shall see. But either way, if you will be using super() in a derived class to initialize the base classes, then the base classes must use super() also. So,

For Python 3:

class A():
    def __init__(self):
        super().__init__()
        self.a = 0

class B():
    def __init__(self):
        super().__init__()
        self.b = 0

class C(A, B):
    def __init__(self):
        super().__init__()

For Python 2 (where classes must be new-style classes) or Python 3

class A(object):
    def __init__(self):
        super(A, self).__init__()
        self.a = 0

class B(object):
    def __init__(self):
        super(B, self).__init__()
        self.b = 0

class C(A, B):
    def __init__(self):
        super(C, self).__init__()
Booboo
  • 38,656
  • 3
  • 37
  • 60
  • I use Python 3. But I don't understand why adding super() in base classes solve the problem? – ThunderPhoenix Nov 25 '19 at 16:49
  • @ThunderPheonix You should read the comment and link posted by Daniel Roseman to your original post, i.e. [Deep Thoughts by Raymond Hettinger](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/), in particular the section **Python’s super() considered super!** and the sub-section **Practical Advice**. – Booboo Nov 25 '19 at 17:05