Python:调用父实例方法
例如,我有下一个代码:Python:调用父实例方法,python,inheritance,polymorphism,python-2.x,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是狗的孩子,它已经超越了instancemetho
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是狗的孩子,它已经超越了instancemethod“树皮”
如何从类“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!!"
class BobyDog( Dog ):
def bark( self ):
BobyDog.bark(self)
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!!
在Python3中,旧样式的类已经被删除;一切都是新样式,您可以从super()
中省略类和self
参数
在旧式类中,调用原始方法的唯一方法是直接引用父类上的未绑定方法并手动传入self
:
class BobyDog( Dog ):
def bark( self ):
super(BobyDog, self).bark()
print "WoOoOoF!!"
class BobyDog( Dog ):
def bark( self ):
BobyDog.bark(self)
print "WoOoOoF!!"