Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: super and __init__() vs __init__( self )

Tags:

python

A:

super( BasicElement, self ).__init__()

B:

super( BasicElement, self ).__init__( self )

What is the difference between A and B? Most examples that I run across use A, but I am running into an issue where A is not calling the parent __init__ function, but B is. Why might this be? Which should be used and in which cases?

like image 603
EmpireJones Avatar asked Oct 02 '11 22:10

EmpireJones


1 Answers

You should not need to do that second form, unless somehow BasicElement class's __init__ takes an argument.

class A(object):
    def __init__(self):
        print "Inside class A init"

class B(A):
    def __init__(self):
        super(B, self).__init__()
        print "Inside class B init"

>>> b = B()
Inside class A init
Inside class B init

Or with classes that need init arguments:

class A(object):
    def __init__(self, arg):
        print "Inside class A init. arg =", arg

class B(A):
    def __init__(self):
        super(B, self).__init__("foo")
        print "Inside class B init"

>>> b = B()
Inside class A init. arg = foo
Inside class B init    
like image 174
jdi Avatar answered Nov 10 '22 09:11

jdi