继承,重写父类
# 父类
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 = f"{self.year} {self.make} {self.model}"
return long_name.title()
def fill_gas_tank(self,tank):
"""方法的描述"""
print("有" + tank + "箱油")
括号内父类类名
# 子类
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
# python 2.7 super(ElectricCar, self).__init__(make, model, year)
self.battery_size = 70 # 子类定义属性
# 重写父类方法
def fill_gas_tank():
"""
子类定义的方法,与父类中方法名称相同,则相当于重写父类方法,
Python将不会考虑这个父类方法,而只关注你在子类中定义的相应方法
"""
print("This car doesn't need a gas tank!")
def describe_battery(self):
"""描述"""
print(f"This car has a {self.battery_size}-kWh battery.")
将实例用作属性
class Car():
...
class Battery:
"""一次模拟电动汽车电瓶的简单尝试"""
def __init__(self, battery_size=40):
"""初始化电瓶的属性"""
self.battery_size = battery_size
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print(f"This car has a {self.battery_size}-kWh battery.")
class ElectricCar(Car):
...
super().__init__(make, model, year)
self.battery = Battery() # 添加了一个名为self.battery的属性,这行代码让Python创建一个新的Battery实例
...
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
#让Python在实例my_tesla中查找属性battery,并对存储在该属性中的Battery实例调用方法describe_battery()
my_tesla.battery.describe_battery()