重写是基于继承的一种方法,也就是说如果我们不想要从父类中继承来的属性或者行为,我们可以在子类中进行方法的重写。
看下面的例子:
class Base:#定义一个父类 def __init__(self,name): self.name = name print('继承了Base') def eat_dinner(self): print(self.name,'晚饭吃火锅') class Student(Base):#继承父类的时候会继承父类中的所有方法 def eat_dinner(self): print(self.name,'晚饭吃自助餐') xiaoming = Student('小明') xiaoming.eat_dinner()
输出结果为:
继承了Base 小明 晚饭吃自助餐
通过这个例子我们可以看出,虽然Student方法继承了Base中的方法并输出了‘继承了Base’,但是当xiaoming使用eat_dinner方法的时候,他使用的是子类重写过后的方法,而不是继承而来的方法。我们在重写的时候需要注意,重写的方法要保持名字和参数的一致性。
本文固定URL:https://www.dotcpp.com/course/644