如果要在子类中引用父类的方法,但是又需要添加一些子类所特有的内容,可通过类名.方法()和super()来调用父类的方法,再个性化子类的对应函数。
直接使用类名.方法()来调用时,还是需要传入self为第一个参数,而使用super()调用则python自动将self传入,因此使用super()比较简洁。
如下animal基类和cat子类,cat类的__init__( )构造函数比父类多一个leg参数,eat()函数比父类多一行输出,通过super()调用父类的函数,则不需要将重复的部分再写一遍。
使用super()调用父类函数的好处:
1.简化代码
2.如果父类名称修改,对其他调用父类函数的类来说也没有影响,而如果直接使用父类的名称来调用,父类名称修改会影响其他所有的类。
class animal:
def __init__(self,name,sex,leg):
self.name = name
self.sex = sex
self.leg = leg
def eat(self,food):
print('%s likes to eat %s'%(self.name,food))
class cat(animal): #cat类继承animal类
def __init__(self,name,sex,leg,tail): #定义初始化构造函数,但是比父类多一个参数
#animal.__init__(self,name,sex,leg)
super().__init__(name,sex,leg) #调用父类的初始化构造函数
self.tail=tail
print('cat has %s legs,and %s tail'%(self.leg,self.tail))
def eat(self,food): #定义eat函数,但是增加一行输出
#animal.eat(self,food)
super().eat(food) #调用父类的方法
print('%s also likes to eat %s' % (self.name, food)) cat1=cat('cat1','male',4,1)
cat1.eat('mouse') # 输出如下:
# cat has 4 legs,and 1 tail
# cat1 likes to eat mouse
# cat1 also likes to eat mouse