1

例如,我有下一个代码:

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 的子代,并且已经覆盖了 instancemethod "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!!
4

1 回答 1

3

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

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

更重要的是,你需要Dogobject它打造成一个新式的类;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 中,旧式类已被移除;一切都是新式的,你可以self省略super().

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

class BobyDog( Dog ):
    def bark( self ):
        BobyDog.bark(self)
        print "WoOoOoF!!"
于 2013-10-24T15:02:54.343 回答