8、设计一个车类 属性:车的类型、车的速度,分别再建立两个子类:小汽车类、电动汽车类去继承车类。 为了实现汽车增加能源的方式,在父类中添加 一个增加能源方法 increased_energy()。 通过汽车对象不同分别实现小汽车类加 油、电动汽车充电的实现
时间: 2024-05-08 19:19:50 浏览: 32
谢谢您的提问。根据您的要求,我可以回答您的问题。下面是答案:
首先,在车类中,我们需要定义车的类型和车的速度两个属性,并添加一个增加能源方法 increased_energy(),代码如下:
```python
class Car:
def __init__(self, car_type, speed):
self.car_type = car_type
self.speed = speed
def increased_energy(self, energy):
pass
```
接下来,我们可以创建两个子类,分别是小汽车类和电动汽车类,代码如下:
```python
class GasolineCar(Car):
def __init__(self, car_type, speed, fuel):
super().__init__(car_type, speed)
self.fuel = fuel
def increased_energy(self, fuel):
self.fuel += fuel
class ElectricCar(Car):
def __init__(self, car_type, speed, battery):
super().__init__(car_type, speed)
self.battery = battery
def increased_energy(self, electricity):
self.battery += electricity
```
我们可以看到,在 GasolineCar 类中,我们添加了一个 fuel 属性,表示汽车的油量,并重写了增加能源方法 increased_energy(),让汽车加油。而在 ElectricCar 类中,我们添加了一个 battery 属性,表示汽车的电量,并重写了增加能源方法 increased_energy(),让汽车充电。
接下来,我们可以创建两个不同的汽车对象,一个是小汽车,一个是电动汽车,然后分别调用它们的增加能源方法,代码如下:
```python
gasoline_car = GasolineCar("小汽车", 60, 10)
gasoline_car.increased_energy(20)
print("小汽车加油后的油量为:", gasoline_car.fuel)
electric_car = ElectricCar("电动汽车", 80, 100)
electric_car.increased_energy(50)
print("电动汽车充电后的电量为:", electric_car.battery)
```
输出结果为:
```
小汽车加油后的油量为: 30
电动汽车充电后的电量为: 150
```
可以看到,我们分别调用了 GasolineCar 类和 ElectricCar 类的 increased_energy() 方法,并且成功地实现了汽车加油和充电的功能。
希望这个回答能够解决您的问题,如果还有其他疑问,欢迎继续提问。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)