声明一个车(vehicle)基类,具有MaxSpeed,Weight等成员变量(私有,使用属性进行读写),Run,Stop等成员函数,由此派生出自行车(bicycle)类,汽车(motorcar)类。自行车(bicycle)类有高度(Height)等属性,汽车(motorcar)类有座位数(SeatNum)等属性。从bicycle和motorcar派生出摩托车(motocycle)类。编写程序验证继承关系。
时间: 2023-06-03 17:02:14 浏览: 339
用c++ 定义一个车(Vehicle)基类,有Run,Stop等成员函数,由此派生出自行车(bicycle)类,汽车(motorcar)
好的,您的问题是如何声明一个车(vehicle)基类,派生出自行车(bicycle)类和汽车(motorcar)类,并从它们派生出摩托车(motorcycle)类,并验证继承关系。
以下是需要编写的代码:
```
class Vehicle:
def __init__(self, max_speed, weight):
self._max_speed = max_speed
self._weight = weight
@property
def max_speed(self):
return self._max_speed
@max_speed.setter
def max_speed(self, value):
self._max_speed = value
@property
def weight(self):
return self._weight
@weight.setter
def weight(self, value):
self._weight = value
def run(self):
print('Vehicle is running.')
def stop(self):
print('Vehicle has stopped.')
class Bicycle(Vehicle):
def __init__(self, max_speed, weight, height):
super().__init__(max_speed, weight)
self._height = height
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
class Motorcar(Vehicle):
def __init__(self, max_speed, weight, seat_num):
super().__init__(max_speed, weight)
self._seat_num = seat_num
@property
def seat_num(self):
return self._seat_num
@seat_num.setter
def seat_num(self, value):
self._seat_num = value
class Motorcycle(Bicycle, Motorcar):
def __init__(self, max_speed, weight, height, seat_num):
Bicycle.__init__(self, max_speed, weight, height)
Motorcar.__init__(self, max_speed, weight, seat_num)
# 验证继承关系
bike = Bicycle(20, 10, 30)
bike.run()
bike.stop()
print(bike.max_speed)
print(bike.weight)
print(bike.height)
car = Motorcar(80, 1000, 5)
car.run()
car.stop()
print(car.max_speed)
print(car.weight)
print(car.seat_num)
moto = Motorcycle(100, 500, 25, 2)
moto.run()
moto.stop()
print(moto.max_speed)
print(moto.weight)
print(moto.height)
print(moto.seat_num)
```
这段代码声明了一个`Vehicle`基类,其中包含了`MaxSpeed`和`Weight`等成员变量,也有`Run`和`Stop`等成员函数。从`Vehicle`类派生出`Bicycle`和`Motorcar`类,并分别在子类中添加了`Height`和`SeatNum`等属性。最后,从`Bicycle`和`Motorcar`类中派生出`Motorcycle`类。
我们验证了继承关系,通过创建`Bicycle`、`Motorcar`和`Motorcycle`对象,并使用基类和派生类的成员函数、属性来操作它们的对象。
阅读全文