1、当父类的中的方法,子类继承后觉得不好用,可以重写方法。
2、重写方法有两种方式
2.1、覆盖父类同名方法
在子类中起和父类同名方法,然后父类中的这个方法在子类中就不可用了
举例:
class animal:
def eat(self):
print("吃")
def sleep(self):
print("睡")
class dog(animal):
def run(self):
print("跑")
def sleep(self):
print("睡111")#覆盖父类方法,被调用时,只会执行子类中同名方法,不会执行父类中的同名方法
2.2、扩展父类同名方法
当需要增加父类中的功能时就可以扩展父类的方法,格式为:super().父类方法()
class animal:
def eat(self): print("吃")
def sleep(self): print("睡")
class dog(animal):
def run(self):
print("跑")
def sleep(self):
super().sleep()#扩展父类方法,被调用时,即执行了父类的方法,又执行了子类扩展的方法
print("睡111")
wangcai = dog()
运行结果:
吃 睡 睡111 跑