python类的继承

1.一个类继承另一个类时,将自动获得另一个类的所有属性和方法。原有的类称为父类,而新类称为子类。子类继承了父类的所有属性和方法,同时还可以定义自己的属性和方法。

# 父类
class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def get_descriptive_name(self):
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def fill_gas_tank(self):
        print("This is gas tank.")

# 子类继承父类的属性和方法
class ElecticCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery_size = 75

    def describe_battery(self):
        print(f"This car has a {self.battery_size}-kWh battery.")

    # 对父类的方法进行重写
    def fill_gas_tank(self):
        print("This car doesn't need a gas tank!")

my_tesla = ElecticCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()

结果:

2019 Tesla Model S
This car has a 75-kWh battery.
This car doesn't need a gas tank!

2.使用代码模拟实物时,可能会给类添加的细节越来越多,属性和方法清单以及文件都越来越长,这时可能需要将类的一部分提取出来,作为一个独立的类。可以将大型类拆分成多个协同工作的小类。

# 父类
class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def get_descriptive_name(self):
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def fill_gas_tank(self):
        print("This is gas tank.")

# 将类的一部分提取出来,作为一个独立的类
class Battery:
    def __init__(self, battery_size=75):
        self.battery_size = battery_size

    def describe_battery(self):
        print(f"This car has a {self.battery_size}-kWh battery.")

    def get_range(self):
        if self.battery_size == 75:
            ranges = 260
        elif self.battery_size == 100:
            ranges = 315

        print(f"This car can go about {ranges} miles on a full charge.")

# 子类继承父类的属性和方法
class ElecticCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        self.battery = Battery()

    # 对父类的方法进行重写
    def fill_gas_tank(self):
        print("This car doesn't need a gas tank!")

my_tesla = ElecticCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.fill_gas_tank()
my_tesla.battery.get_range()

结果:

2019 Tesla Model S
This car has a 75-kWh battery.
This car doesn't need a gas tank!
This car can go about 260 miles on a full charge.

你可能感兴趣的:(python,开发语言)