定义一个车(vehicle)基类,具有Speed、Weight等成员变量,Run、Stop等成员函数,由此派生出自行车(bicycle)类,汽车(motorcar)类。自行车(bicycle)类有高度(Height)等属性,汽车(motorcycle)类有座位数(SeatNum)等属性。从bicycle和motorcycle派生出摩托车(Motorcar)类。完成这些类,使得测试代码可以运行并得到正确的输出结果。
时间: 2023-12-18 07:05:58 浏览: 208
以下是代码实现:
```python
class Vehicle:
def __init__(self, speed, weight):
self.speed = speed
self.weight = weight
def run(self):
print("Vehicle is running.")
def stop(self):
print("Vehicle has stopped.")
class Bicycle(Vehicle):
def __init__(self, speed, weight, height):
super().__init__(speed, weight)
self.height = height
class Motorcycle(Vehicle):
def __init__(self, speed, weight, seat_num):
super().__init__(speed, weight)
self.seat_num = seat_num
class Motorcar(Bicycle, Motorcycle):
def __init__(self, speed, weight, height, seat_num):
Bicycle.__init__(self, speed, weight, height)
Motorcycle.__init__(self, speed, weight, seat_num)
```
测试代码:
```python
vehicle = Vehicle(60, 1000)
vehicle.run()
vehicle.stop()
bicycle = Bicycle(20, 10, 1.5)
print("Bicycle speed:", bicycle.speed)
print("Bicycle weight:", bicycle.weight)
print("Bicycle height:", bicycle.height)
motorcycle = Motorcycle(100, 500, 2)
print("Motorcycle speed:", motorcycle.speed)
print("Motorcycle weight:", motorcycle.weight)
print("Motorcycle seat number:", motorcycle.seat_num)
motorcar = Motorcar(80, 800, 1.2, 4)
print("Motorcar speed:", motorcar.speed)
print("Motorcar weight:", motorcar.weight)
print("Motorcar height:", motorcar.height)
print("Motorcar seat number:", motorcar.seat_num)
```
输出结果:
```
Vehicle is running.
Vehicle has stopped.
Bicycle speed: 20
Bicycle weight: 10
Bicycle height: 1.5
Motorcycle speed: 100
Motorcycle weight: 500
Motorcycle seat number: 2
Motorcar speed: 80
Motorcar weight: 800
Motorcar height: 1.2
Motorcar seat number: 4
```
阅读全文