前言
我们前面说了,子类继承于父类,可以调用父类的所有属性和方法。那么如果我们想在继承的过程中重新书写父类的某些方法,此时就用到了方法重写。我们通常采用如下方式进行方法重写:
class 父类:
def 父类方法1(self):
方法1的具体执行方式
class 子类(父类):
def 父类方法1(self):
重写父类方法1的执行方式
实践
我们这里首先创建一个名为Animal
的父类,并定义其方法eat()
:
class Animal:
def eat(self):
print("This animal is eating")
然后我们定义子类Rabbit
继承于父类Animal
,同时对方法eat()
进行重写:
class Rabbit(Animal):
def eat(self):
print("This rabbit is eating carrot")
其实就是定义一个与父类中同名的函数然后编写你想执行的代码即可。我们对子类实例化:
rabbit = Rabbit()
rabbit.eat()
>>> This rabbit is eating carrot
可见此时执行的是子类中的eat()
方法。
以上便是方法重写的全部内容,感谢大家的收藏、点赞、评论。我们下一节将介绍方法链(Method Chaining),敬请期待~