Python code for) the HybridCar class: Car - speed: int = 0 + increase_speed(amount: int) + get_speed: int PetrolCar ElectricCar + accelerate) + accelerate() HybridCar + mode: str = "electric" + accelerate) The Car class' increase_ speed() method increases the speed attribute by the amount passed in as an argument. The PetrolCar class' accelerate() method calls Car class' increase_ speed() method with an amount of 20, while the ElectricCar class' accelerate() method calls the same method with an amount of 10. The HybridCar class' accelerate() method should call either the PetrolCar's or ElectricCar's accelerate() method depending on the mode attribute. The following code that makes use of the HybridCar class should produce
时间: 2024-02-06 22:04:27 浏览: 18
Here is the Python code for the HybridCar class:
```python
class Car:
speed: int = 0
def increase_speed(self, amount: int):
self.speed += amount
def get_speed(self) -> int:
return self.speed
class PetrolCar(Car):
def accelerate(self):
self.increase_speed(20)
class ElectricCar(Car):
def accelerate(self):
self.increase_speed(10)
class HybridCar:
mode: str = "electric"
petrol_car: PetrolCar = PetrolCar()
electric_car: ElectricCar = ElectricCar()
def accelerate(self):
if self.mode == "electric":
self.electric_car.accelerate()
else:
self.petrol_car.accelerate()
```
In this code, we first define the Car class with a speed attribute, and the increase_speed() and get_speed() methods. Then we define the PetrolCar and ElectricCar classes, which inherit from the Car class and override the accelerate() method to call the increase_speed() method with different amounts.
Finally, we define the HybridCar class with a mode attribute that determines whether to use the PetrolCar or ElectricCar's accelerate() method. The accelerate() method simply calls the appropriate method based on the mode attribute.
Here is an example of how to use the HybridCar class:
```python
car = HybridCar()
print(car.get_speed()) # 0
car.accelerate()
print(car.get_speed()) # 10
car.mode = "petrol"
car.accelerate()
print(car.get_speed()) # 30
```
In this example, we create a new instance of the HybridCar class and call its accelerate() method twice with different modes, which results in different amounts being added to the speed attribute. We then print the speed attribute after each call to verify that it has been updated correctly.