简体   繁体   English

Python:调用parent instancemethod

[英]Python: call parent instancemethod

For example, I have next code: 例如,我有下一个代码:

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 is a child of Dog and have overrided instancemethod "bark". BobyDog是Dog的孩子,并且已经超越了实例方法“bark”。

How I can refer to parent method "bark" from instance of class "BobyDog"? 我如何从类“BobyDog”的实例中引用父方法“bark”?

In other words: 换一种说法:

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

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

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

You need to call the super() function, and pass in the current class ( BobyDog ) and self : 你需要调用 super()函数,并传入当前类( BobyDog )和self

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

More importantly, you need to base Dog on object to make it a new-style class; 更重要的是,你需要将Dog放在object以使其成为一种新式的类; super() does not work with old-style classes: super()不适用于旧式类:

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

With these changes the call works: 通过这些更改,呼叫有效:

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

In Python 3, old-style classes have been removed; 在Python 3中,旧式类已被删除; everything is new-style, and you can omit the class and self parameters from super() . 一切都是新式的,你可以省略super()的类和self参数。

In old-style classes, the only way to call the original method is by referring directly to the unbound method on the parent class and manually pass in self : 在旧式类中,调用原始方法的唯一方法是直接引用父类的未绑定方法并手动传入self

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM