1、在现实生活中,机动车一般有两种作用,一种是载人,一种是载物,这可以看作两种运行方法,设计程序模拟客车和货车的运行,反映出客车载人数和货车载物数。 (1)定义车类Car,包括名称属性name,以及运行方法run()。 (2)定义客车类TaxiCar,包括名称属性name,载人属性person_num,以及运行方法run()。 (3)定义货车类FreightCar,包括名称属性name,载物属性goods_weight,以及运行方法run()。 创建客车类和货车类的实例对象,并调用其运行方法
时间: 2024-02-15 09:02:29 浏览: 25
好的,我理解了你的问题。以下是 Python 代码实现:
```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 running with {self.person_num} persons.")
# 定义货车类
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 running with {self.goods_weight} kg goods.")
# 创建客车类和货车类的实例对象并调用其运行方法
taxi = TaxiCar("Taxi", 4)
taxi.run()
freight = FreightCar("Freight", 1000)
freight.run()
```
输出结果:
```
Taxi is running with 4 persons.
Freight is running with 1000 kg goods.
```