在类的继承中,如果重定义某个方法,该方法会覆盖父类的同名方法,但有时,我们希望能同时实现父类的功能,这时,我们就需要调用父类的方法了,可通过使用 super
来实现,比如:
#-------- python2写法
class Animal(object):
def __init__(self, name):
self.name = name
def greet(self):
print 'Hello, I am %s.' % self.name
class Dog(Animal):
def greet(self):
super(Dog, self).greet() # Python3 可使用 super().greet()
print 'WangWang...'
#-------- python3 写法
class Animal():
def __init__(self, name):
self.name = name
def greet(self):
print ('Hello, I am %s.' % self.name)
class Dog(Animal):
def greet(self):
super().greet() # Python3 可使用 super().greet()
print ('WangWang...')
注: python2 和python3的写法有些不一致,Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :
在上面&#