例如,我有下一个代码:
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/