开发者

Methods of the same name and inheritance, Python

I have an odd question, and seeing as the real context is fairly complex I've made a simple example. I have two classes Base and Child. Each share a method of the the same name go. What I want the Child class to be able to do is inherit the go method from Base. However, when I call 开发者_JS百科the go method on Child I want it to do some things (In this case multiply the attribute A by 2), then call the go method that it inherited from Base.

In this example calling go on Base would print 35, while I want Child to print 70.

class Base :
    def __init__ (self) :
        self.A = 35

    def go (self) :
        print self.A


class Child (Base) :
    def __init__ (self) :
        Base.__init__(self)

    def go (self) :
        self.A = self.A * 2

        # Somehow call Base's **go** method, which would print 70.

I understand that it's typically not a good idea to do this (seeing as it could be confusing), however in the context of what I'm doing it makes sense.


This is absolutely a fine thing to do. What you're looking for is super().

class Child (Base):
    def __init__ (self):
        super(Child, self).__init__()

    def go(self):
        self.A = self.A * 2
        super(Child, self).go()

In Python 3 you can use it without arguments because it will detect the correct ones automatically.

Edit: super() is for new-style classes, which you should use anyway. Just declare any class which doesn't inherit from another as inheriting from object:

class Base(object):

Also, all those extra spaces before and after parenthesis are not considered good python style, see PEP8.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜