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

Here is an example of calling

__init__()

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

mrotest.py:

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")
    c.helloC()
    
if __name__ == '__main__':
    main()

Running the program gives this output:

$ python mrotest.py 
Calling A:  42
Calling B:  Joe

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.