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()
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__()