super or not super?

Thomas Jollans tjol at tjol.eu
Fri Jul 12 10:30:11 EDT 2019


On 12/07/2019 16.12, Paulo da Silva wrote:
> Hi all!
>
> Is there any difference between using the base class name or super to
> call __init__ from base class?

There is, when multiple inheritance is involved. super() can call
different 'branches' of the inheritance tree if necessary.


Let me demonstrate:


class A1:
    def __init__(self):
        super().__init__()
        print('A1 called')

class B1(A1):
    def __init__(self):
        super().__init__()
        print('B1 called')

class C1(A1):
    def __init__(self):
        super().__init__()
        print('C1 called')

class D1(B1,C1):
    def __init__(self):
        super().__init__()
        print('D1 called')


class A2:
    def __init__(self):
        object.__init__(self)
        print('A2 called')

class B2(A2):
    def __init__(self):
        A2.__init__(self)
        print('B2 called')

class C2(A2):
    def __init__(self):
        A2.__init__(self)
        print('C2 called')

class D2(B2,C2):
    def __init__(self):
        super().__init__()
        print('D2 called')

if __name__ == '__main__':
    D1()
    print('---')
    D2()


##############


% python3 super_demo.py
A1 called
C1 called
B1 called
D1 called
---
A2 called
B2 called
D2 called


>
> class C1:
> 	def __init__(self):
> 		...
>
> class C2(C1):
> 	def __init__(self):
> 		C1.__init__(self) or super().__init__() ??
> 		...
>
> I have been using super, but I see some scripts where the base class
> name is used.

Just use super(), especially in __init__.





More information about the Python-list mailing list