0

If we have class A, defined as follows,

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

why do most people use

class B(A):
    def __init__(self, x, y):
        super().__init__(x)
        self.y = y

instead of

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

? I think A.__init__(self, x) is better then super().__init__(x) because it supports multiple inheritance (and I didn't find a way to do it with super()):

class A:
    def __init__(self, x):
        self.x = x
class B:
    def __init__(self, y):
        self.y = y
class C(A, B):
    def __init__(self, x, y, z):
        A.__init__(self, x)
        B.__init__(self, y)
        self.z = z

When I try to use super() in the previous example, like this:

class A:
    def __init__(self, x):
        self.x = x
class B:
    def __init__(self, y):
        self.y = y
class C(A, B):
    def __init__(self, x, y, z):
        super().__init__(self, x)
        super().__init__(self, y)
        self.z = z

class C doesn't have attribute y (try: c = C(1, 2, 3) and print(c.y) in next line).

What am I doing wrong?

jub0bs
  • 60,866
  • 25
  • 183
  • 186
knowledge
  • 383
  • 3
  • 15
  • `super` is **precisely for** multiple inheritance, so you don't have to go through explicitly calling the method on the all of the individual superclasses. – jonrsharpe Jan 09 '15 at 11:09

1 Answers1

0

I you use super().__init__(), Python will automatically call all constructors of your base classes on its own in the right order (in your second example first A, then Bconstructors).

This is one of the beauty of Python, it handles multiple inheritance nicely :).

Plouff
  • 3,290
  • 2
  • 27
  • 45