类的继承

类的继承:四大支柱(抽象、多态、继承、封装)之一,优点:代码重用

class Car():
    def __init__(self, make, model, year):
        #初始化描述汽车的属性
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
    def get_descriptive_name(self):
        #返回整洁的描述性信息
        long_name = str(self.year) + " " + self.make + " " + self.model
        return long_name.title()
    def read_odometer(self):
        #打印汽车的里程信息
        return ("This car has " + str(self.odometer_reading) + " miles on it")
    def update_odometer(self,mileage):
        #将里程表读书设置为指定的值
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            return ("You can't roll back an odometer!")
    def increment(self,miles):
        #将里程表读数增加指定的量
        self.odometer_reading += miles
        return self.odometer_reading
    def fill_gas_tank(self):
        return ("Yes, gas is necessary!")
class Electriccar(Car):
        #继承父类Car
    def __init__(self, make, model, year):
        #初始化父类的属性,再初始化电动汽车的特有属性
        super().__init__(make, model, year)
        self.battery_size = 70
    def describe_battery(self):
        return ("This car has a" + str(self.battery_size) + "-kwh battery.")
    def fill_gas_tank(self):
        #重写父类方法
        return ("This car does't need a gas tank.")

my_tesla = Electriccar("tesla", "model s", 2016)   #子类属性初始化
print(my_tesla.get_descriptive_name())     #调用父类方法
my_tesla.increment(30)    #调用父类方法
my_tesla.update_odometer(30)
print(my_tesla.read_odometer())
print(my_tesla.fill_gas_tank())  #重写父类方法后,不使用父类方法,只运行子类方法

输出结果:

2016 Tesla Model S
This car has 30 miles on it
This car does't need a gas tank.

Process finished with exit code 0

类的继承分为单一继承和多继承,多继承指多个子类继承一个父类。

上一篇:一个实验看懂 Kconfig 、menuconfig和.config 之间的关系


下一篇:2020.1.12