Python:调用父实例方法

标签 python inheritance polymorphism python-2.x

例如,我有下一个代码:

class Dog:
    def bark(self):
        print "WOOF"

class BobyDog( Dog ):
    def bark( self ):
        print "WoOoOoF!!"

otherDog= Dog()
otherDog.bark() # WOOF

boby = BobyDog()
boby.bark() # WoOoOoF!!

BobyDog 是 Dog 的子级,并且已重写实例方法“bark”。

如何从“BobyDog”类的实例引用父方法“bark”?

换句话说:

class BobyDog( Dog ):
    def bark( self ):
        super.bark() # doesn't work
        print "WoOoOoF!!"

otherDog= Dog()
otherDog.bark() # WOOF

boby = BobyDog()
boby.bark()
# WOOF
# WoOoOoF!!

最佳答案

您需要调用super()函数,并传入当前类(BobyDog)和self:

class BobyDog( Dog ):
    def bark( self ):
        super(BobyDog, self).bark()
        print "WoOoOoF!!"

更重要的是,你需要将Dog建立在object之上,使其成为一个新式的类; super() 不适用于旧式类:

class Dog(object):
    def bark(self):
        print "WOOF"

通过这些更改,调用可以正常工作:

>>> class Dog(object):
...     def bark(self):
...         print "WOOF"
... 
>>> class BobyDog( Dog ):
...     def bark( self ):
...         super(BobyDog, self).bark()
...         print "WoOoOoF!!"
... 
>>> BobyDog().bark()
WOOF
WoOoOoF!!

在Python 3中,旧式类已被删除;一切都是新风格的,您可以省略 super() 中的 class 和 self 参数。

在旧式类中,调用原始方法的唯一方法是直接引用父类上的未绑定(bind)方法并手动传入self:

class BobyDog( Dog ):
    def bark( self ):
        BobyDog.bark(self)
        print "WoOoOoF!!"

关于Python:调用父实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19569556/

相关文章:

python - Numpy 连接列表,其中第一列在范围 n 内

python - 使用zerorpc和线程的程序将引发异常 “LoopExit: This operation would block forever”

C++更改子类中拥有的对象类型

c++ - 如何在C++中实现继承并解决错误 "parent class is not accessible base of child class"?

java - jackson :以编程方式确定子类型

Python。 Selenium 。拖放错误 'AttributeError: move_to requires a WebElement'

python - Flask 模板 - For 循环迭代键 :value

c++ - 通过构造函数动态确定类实现

c++ - 从 Base* 的容器向下转换为 Derived* 而无需显式转换

c++ - 模板、多态性、抽象基类指针和运行时转换