【问题标题】:Methods of the same name and inheritance, Python同名和继承的方法,Python
【发布时间】:2011-10-23 14:32:25
【问题描述】:

我有一个奇怪的问题,鉴于实际情况相当复杂,我做了一个简单的例子。我有两个类 BaseChild。每个共享一个同名的方法 go。我希望 Child 类能够做的是从 Base 继承 go 方法。但是,当我在 Child 上调用 go 方法时,我希望它做一些事情(在这种情况下,将属性 A 乘以 2),然后调用它从 Base 继承的 go 方法。

在此示例中,在 Base 上调用 go 将打印 35,而我希望 Child 打印 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.

我知道这样做通常不是一个好主意(因为它可能会造成混淆),但是在我正在做的事情的背景下是有道理的。

【问题讨论】:

    标签: python class inheritance methods


    【解决方案1】:

    这绝对是一件好事。你要找的是super()

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

    在 Python 3 中,您可以不带参数地使用它,因为它会自动检测正确的参数。

    编辑:super() 用于新型类,无论如何你都应该使用它。只需将任何不从另一个继承的类声明为从object 继承即可:

    class Base(object):
    

    另外,括号前后所有多余的空格都不是好的python样式,请参阅PEP8

    【讨论】:

    • 嗯,在 2.7 中这似乎不起作用。我收到错误 TypeError: must be type, not classobj
    • 它有效。您需要使用新型类(无论如何它们更好)。只需将class Base : 更改为class Base(object) :
    • @PeterMortensen 编辑必须是实质性的;积极阅读不是进行琐碎编辑的可接受理由。
    猜你喜欢
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多