2.请定义一个交通工具(Vehicle)类,其具有的属性和方法如下: 属性: 1)速度-speed; 2) 长度-length;3) 宽度-width;4) 高度-height; 方法: 1)移动-move() 2) 加速-speedUp(int num) num: 表示在当前速度上增加的速度值 3) 减速-speedDown(int num) num: 表示在当前速度上减低的速度值 4)对Vehicle类的各个内部字段使用setter/getter 进行封装 5) 创建测试代码,设置输出一个Vehicle对象的各个属性,并测试speedUp()和speedDown()方法。
时间: 2024-02-22 17:00:46 浏览: 95
好的,以下是交通工具(Vehicle)类的代码实现:
```python
class Vehicle:
def __init__(self, speed, length, width, height):
self._speed = speed
self._length = length
self._width = width
self._height = height
def move(self):
print("Vehicle is moving...")
def speedUp(self, num):
self._speed += num
def speedDown(self, num):
self._speed -= num
def setSpeed(self, speed):
self._speed = speed
def getSpeed(self):
return self._speed
def setLength(self, length):
self._length = length
def getLength(self):
return self._length
def setWidth(self, width):
self._width = width
def getWidth(self):
return self._width
def setHeight(self, height):
self._height = height
def getHeight(self):
return self._height
```
接下来是测试代码,我们创建了一个Vehicle对象,并设置了它的各个属性。然后我们使用speedUp()方法将速度增加了50,使用speedDown()方法将速度减少了20,并输出当前速度。
```python
vehicle = Vehicle(100, 5, 2, 2)
print("Speed:", vehicle.getSpeed())
print("Length:", vehicle.getLength())
print("Width:", vehicle.getWidth())
print("Height:", vehicle.getHeight())
vehicle.speedUp(50)
print("Speed up:", vehicle.getSpeed())
vehicle.speedDown(20)
print("Speed down:", vehicle.getSpeed())
```
输出结果为:
```
Speed: 100
Length: 5
Width: 2
Height: 2
Speed up: 150
Speed down: 130
```
阅读全文