views:

101

answers:

5

I want to be able to subclass a class, and define __init__ but still run the old __init__ as well.

To illustrate, say I have the following classes:

class A(object):
    def __init__(self):
        self.var1 = 1

class B(A):
    def __init__(self)
        self.var2 = 2
        doInitForA()

And I want to be able to do this:

instB = B()
print (instB.var1) #1
print (instB.var2) #2

Edited as Ignacio Vazquez-Abrams suggested. (Is it possible to edit without bumping?)

A: 

Either call a.__init__(self) or derive a from object and use super().

Ignacio Vazquez-Abrams
I really don't know why I didn't think of this XD
Wallacoloo
A: 
class a:
    def __init__(self):
        self.var1 = 1

class b(a):
    def __init__(self)
        self.var2 = 2
        a.__init__(self)

You can even write super().__init__() if you are using python 3.
See this question about the use of super().

Li0liQ
A: 

Call your father's c'tor from within your c'tor: a.__init__(self). Note that you need to pass self as first parameter. If the parent c'tor takes more parameters, pass them after self.

Alexander Gessler
+3  A: 

replace

doInitForA()

with

super(b, self).__init__()
Mike Sherov
+3  A: 

You might want to look at this question: http://stackoverflow.com/questions/904036/chain-calling-parent-constructors-in-python, specifically use the super(b, self).__init__() method.

Ninefingers