三十、Python基础语法(继承-下)
方法重写
重写:在子类中定义和父类中名字相同的方法,如果父类中方法不能满足子类对象的需求,重写的形式有覆盖和扩展
一、覆盖式重写
class Vehicle:
def move(self):
print("The vehicle is moving in a general way.")
class Car(Vehicle):
# 重写move方法
def move(self):
print("The car is driving on the road.")
class Bicycle(Vehicle):
# 重写move方法
def move(self):
print("The bicycle is being pedaled.")
vehicle = Vehicle()
vehicle.move() # The vehicle is moving in a general way.
car = Car()
car.move() # The car is driving on the road.
bicycle = Bicycle()
bicycle.move() # The bicycle is being pedaled.
二、扩展式重写
扩展式重写:指父类中原有的功能保留,在此基础上添加新的功能代码。
实现:在子类中定义和父类名字相同的方法,使用 super().父类方法名(父类方法参数)来调用父类中的方法,然后再书写新的功能代码
class Animal:
def make_sound(self):
print("Animal makes a sound.")
class Dog(Animal):
def make_sound(self):
# 先调用父类的方法
super().make_sound()
print("Dog barks.")
class Cat(Animal):
def make_sound(self):
# 先调用父类的方法
super().make_sound()
print("Cat meows.")
dog = Dog()
dog.make_sound()
cat = Cat()
cat.make_sound()
运行结果: