python定义一个交通工具的类
时间: 2024-06-08 18:04:17 浏览: 194
在Python中,你可以定义一个名为`Vehicle`的类来表示一般的交通工具,这个类可以包含一些通用属性(如品牌、型号、颜色)和方法(如启动、停止、行驶)。下面是一个简单的示例:
```python
class Vehicle:
def __init__(self, brand, model, color):
self.brand = brand
self.model = model
self.color = color
self.is_running = False
# 定义启动方法
def start(self):
if not self.is_running:
print(f"{self.brand} {self.model} is starting.")
self.is_running = True
else:
print("Vehicle is already running.")
# 定义停止方法
def stop(self):
if self.is_running:
print(f"{self.brand} {self.model} is stopping.")
self.is_running = False
else:
print("Vehicle is already stopped.")
# 定义行驶方法
def drive(self, distance):
if self.is_running:
print(f"{self.brand} {self.model} is driving {distance} km.")
else:
print("Cannot drive, vehicle is not running.")
# 示例使用
my_car = Vehicle("Toyota", "Corolla", "Red")
my_car.start()
my_car.drive(50)
my_car.stop()
```
阅读全文