开发者

Polymorphism - adding to existing methods while overwriting them

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

To illustrate, s开发者_如何学Goay 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?)


replace

doInitForA()

with

super(b, self).__init__()


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


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


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().


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜