用Python 建立一个汽车类,包括: (1)属性:汽车颜色color、车身重量weight(私有属性)、速度speed。 构造函数:能初始化各个属性值(speed初始值设为50)。 (2)方法: speedup():将属性值speed+10并显示speed值; speedcut():将属性值speed-10并显示speed值; show():显示属性值color、weight、speed。 (3)在主程序中创建实例并初始化各属性值,调用show方法、加速方法、减速方法。 (4)输出运行结果。
时间: 2024-01-17 14:02:35 浏览: 25
好的,下面是使用 Python 编写的汽车类,以及在主程序中创建实例并进行调用的代码,请您复制以下代码并在 Python 环境下运行。
```python
class Car:
def __init__(self, color, weight):
self.color = color
self.__weight = weight
self.speed = 50
def speedup(self):
self.speed += 10
print("当前速度为:", self.speed)
def speedcut(self):
self.speed -= 10
print("当前速度为:", self.speed)
def show(self):
print("汽车颜色为:", self.color)
print("汽车重量为:", self.__weight, "吨")
print("当前速度为:", self.speed)
car = Car("红色", 1.5)
car.show() # 输出汽车属性
car.speedup() # 汽车加速
car.speedcut() # 汽车减速
```
程序的运行结果如下:
```
汽车颜色为: 红色
汽车重量为: 1.5 吨
当前速度为: 50
当前速度为: 60
当前速度为: 50
```
在程序中,我们定义了一个汽车类 `Car`,包含了汽车的颜色、重量和速度等属性,以及加速、减速和展示汽车属性信息的方法。其中,重量属性被设置为私有属性,只能在类的内部访问。
在主程序中,我们创建了一个 `Car` 类的实例 `car`,并初始化其颜色和重量属性。然后,我们先调用 `show()` 方法,展示汽车的属性信息。接着,我们调用 `speedup()` 方法,将汽车的速度加快,并使用 `print()` 函数输出当前速度。最后,我们再次调用 `speedcut()` 方法,将汽车的速度降低,并使用 `print()` 函数输出当前速度。
希望我的回答能够帮到您,如有问题请随时追问。