Calling __init__() on all base classes in Python multiple heritance

Here is an example of calling


for all base classes, when doing multiple inheritance in Python (mixins). It uses *args and **kwargs syntax:

class A(object):
    def __init__(self, *args, **kwargs):
        super(A, self).__init__(*args, **kwargs)
        self.number = kwargs['number']
    def helloA(self):
        return self.number
class B(object):
    def __init__(self, *args, **kwargs):
        super(B, self).__init__()
        self.message = kwargs['message']
    def helloB(self):
        return self.message
class C(A,B):
    def __init__(self, *args, **kwargs):
        # Notice: only one call to super... due to mro
        super(C, self).__init__(*args, **kwargs)
    def helloC(self):
        print "Calling A: ", self.helloA()
        print "Calling B: ", self.helloB()  
def main():
    c = C(number=42, message="Joe")
if __name__ == '__main__':

Running the program gives this output:

$ python 
Calling A:  42
Calling B:  Joe

Leave a Reply