现实生活中,机动车一般有两种作用,一种是载人,一种是载物,可以看做是两种运行方法。设计程序模拟客车和货车的运行,反映出客车载人 数和货车载人数 (1) 定义车类Car,包括属性名name,以及运行 方法run 2)定义客车类TaxiCar,包括属性名name,载人属性 person num,以及运行方法run0. (3)定义货车类FreightCar,包括属性名name,载货 属性goods_wight,以及运行方法run0. (④创建客车类和货车类的实例,并调用运行方法
时间: 2023-12-10 18:39:38 浏览: 147
设计一个Car类
以下是Python3的代码实现:
```python
class Car:
def __init__(self, name):
self.name = name
def run(self):
print(f"{self.name} is running.")
class TaxiCar(Car):
def __init__(self, name, person_num):
super().__init__(name)
self.person_num = person_num
def run(self):
print(f"{self.name} is carrying {self.person_num} passengers and running.")
class FreightCar(Car):
def __init__(self, name, goods_weight):
super().__init__(name)
self.goods_weight = goods_weight
def run(self):
print(f"{self.name} is carrying {self.goods_weight} tons of goods and running.")
taxi_car = TaxiCar("Taxi", 4)
taxi_car.run()
freight_car = FreightCar("Freight", 10)
freight_car.run()
```
输出:
```
Taxi is carrying 4 passengers and running.
Freight is carrying 10 tons of goods and running.
```
阅读全文