Search code examples
pythonpython-3.xpython-2.7super

How to use Super() in Python 2.7 for multiple inheritance


Using super in python 2.7 results in error code,

TypeError: super() takes at least 1 argument (0 given)


Solution

  • Following code can help in understanding how to use the super function for multiple inheritance in python 2.7,

    class A(object):
        def __init__(self):
            print("Class A")
            super(A, self).__init__()
    
    
    class B(object):
        def __init__(self):
            print("Class B")
            super(B, self).__init__()
    
    
    class C(A, B):
    
        def __init__(self):
            print("Class C")
            super(C, self).__init__()
    
    
    Cobj = C()
    

    In Python 3, super function is a bit simplified and can be used as follows,

    class A:
        def __init__(self):
            print("Class A")
            super().__init__()
    
    
    class B:
        def __init__(self):
            print("Class B")
            super().__init__()
    
    
    class C(A, B):
    
        def __init__(self):
            print("Class C")
            super().__init__()
    
    
    Cobj = C()
    

    If you run the above code in python 2.7, you will get this error message,

    TypeError: super() takes at least 1 argument (0 given)

    Most books assume python- 3.x is being used in all productions, which is not the case. So code style and patterns from 2.7 are still very relevant for developers.