2

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?)

Ponkadoodle
  • 5,777
  • 5
  • 38
  • 62

5 Answers5

6

replace

doInitForA()

with

super(b, self).__init__()
Mike Sherov
  • 13,277
  • 8
  • 41
  • 62
3

You might want to look at this question: Chain-calling parent constructors in python, specifically use the super(b, self).__init__() method.

Community
  • 1
  • 1
0

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0
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().

Community
  • 1
  • 1
Li0liQ
  • 11,158
  • 35
  • 52
0

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
  • 45,603
  • 7
  • 82
  • 122