例如,我有下一个代码:
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!!
答案 0 :(得分:3)
您需要调用 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中,旧式类已被删除;一切都是新式的,您可以省略self
中的类和super()
参数。
在旧式类中,调用原始方法的唯一方法是直接引用父类的未绑定方法并手动传入self
:
class BobyDog( Dog ):
def bark( self ):
BobyDog.bark(self)
print "WoOoOoF!!"