编写一个汽车类Car,实例属性包括汽车品牌brand,汽车型号model,生产年份year,里程读数odometer_reading(初始值是0); 实例方法showInfo打印对象的属性信息 实例方法update_odometer()设置实例对象的里程读数odometer_reading;如果设置的值大于当前的里程读数才能设置成功;否则不能设置 实例方法increment_odometer() 设置增加里程读数odometer_reading的值 编写一个电车类ElectricCar继承于Car类,ElectricCar类在继承Car类的所有属性的同时比Car类多一个实例属性battery_size初始值为70 电车类ElectricCar重写Car类的showInfo方法,打印ElectricCar类对象的所有的属性信息 电车类的实例方法set_battery() 设置battery_size的值
时间: 2024-02-18 09:05:47 浏览: 130
好的,以下是Car类和ElectricCar类的代码实现:
```python
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
self.odometer_reading = 0
def showInfo(self):
print("Brand:", self.brand)
print("Model:", self.model)
print("Year:", self.year)
print("Odometer Reading:", self.odometer_reading)
def update_odometer(self, mileage):
if mileage > self.odometer_reading:
self.odometer_reading = mileage
print("Odometer reading set to", self.odometer_reading)
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
print("Odometer reading incremented by", miles, "miles.")
class ElectricCar(Car):
def __init__(self, brand, model, year):
super().__init__(brand, model, year)
self.battery_size = 70
def showInfo(self):
print("Brand:", self.brand)
print("Model:", self.model)
print("Year:", self.year)
print("Odometer Reading:", self.odometer_reading)
print("Battery Size:", self.battery_size)
def set_battery(self, size):
self.battery_size = size
print("Battery size set to", self.battery_size)
```
接下来我们可以创建一个Car对象和一个ElectricCar对象,并调用它们的方法:
```python
my_car = Car("Toyota", "Camry", 2021)
my_car.showInfo()
my_car.update_odometer(100)
my_car.increment_odometer(50)
my_car.showInfo()
my_electric_car = ElectricCar("Tesla", "Model S", 2022)
my_electric_car.showInfo()
my_electric_car.update_odometer(200)
my_electric_car.increment_odometer(80)
my_electric_car.showInfo()
my_electric_car.set_battery(90)
my_electric_car.showInfo()
```
输出结果如下:
```
Brand: Toyota
Model: Camry
Year: 2021
Odometer Reading: 0
Odometer reading set to 100
Odometer reading incremented by 50 miles.
Brand: Toyota
Model: Camry
Year: 2021
Odometer Reading: 150
Battery Size: 70
Brand: Tesla
Model: Model S
Year: 2022
Odometer Reading: 0
Battery Size: 70
Odometer reading set to 200
Odometer reading incremented by 80 miles.
Brand: Tesla
Model: Model S
Year: 2022
Odometer Reading: 280
Battery Size: 90
```
阅读全文