102.(2)
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):
print("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:
print("You can't roll back an odometer!")
def increment_odometer(self , miles):
self.odometer_reading += miles
class ElectricCar(Car):
'''Represent aspects of a car, specific to electric vehicles.'''
def __init__(self , make ,model ,year):
"""
电动汽车的独特之处
初始化父类的属性,再初始化电动汽车特有的属性
"""
super().__init__(make ,model ,year)
self.battery_size = 70 # 添加了新属性self.battery_size
# 这个属性子类所有实例都包含,但所有Car实例都不包含
def describe_battery(self):
'''打印一条描述电瓶容量的消息'''
print("This car has a " + str(self.battery_size) + "-kwh battery.")
def read_odometer(self): # 可以建立一个和父类相同的方法,进行重写
print("This car doesn't need a gas tank!")
my_tesla = ElectricCar('tesla' , 'model s' , 2016) # 创建一个实例
print(my_tesla.get_descriptive_name()) # 子类可以调用父类的方法
my_tesla.describe_battery() #调用子类中的方法
my_tesla.read_odometer() # 直接调用和父类相同的方法,系统默认子类继承的方法
来源:CSDN
作者:weixin_45707364
链接:https://blog.csdn.net/weixin_45707364/article/details/103943067