三十、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()

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值