python设计一个类代表机动车
时间: 2023-07-14 13:13:20 浏览: 93
python102个源码实例 毕业设计
可以设计一个名为Vehicle的类,代表机动车。这个类可以有以下属性:
- make:制造商
- model:型号
- year:年份
- color:颜色
- mileage:里程数
同时,这个类可以有以下方法:
- start_engine():启动引擎
- stop_engine():关闭引擎
- drive(distance):驾驶指定的距离,更新里程数
- get_make():获取制造商信息
- get_model():获取型号信息
- get_year():获取年份信息
- get_color():获取颜色信息
- get_mileage():获取里程数信息
下面是一个简单的实现:
```python
class Vehicle:
def __init__(self, make, model, year, color, mileage):
self.make = make
self.model = model
self.year = year
self.color = color
self.mileage = mileage
def start_engine(self):
print("Starting engine...")
def stop_engine(self):
print("Stopping engine...")
def drive(self, distance):
print(f"Driving {distance} miles...")
self.mileage += distance
def get_make(self):
return self.make
def get_model(self):
return self.model
def get_year(self):
return self.year
def get_color(self):
return self.color
def get_mileage(self):
return self.mileage
```
使用示例:
```python
my_car = Vehicle("Toyota", "Camry", 2018, "blue", 15000)
print(my_car.get_make()) # 输出:Toyota
print(my_car.get_model()) # 输出:Camry
print(my_car.get_year()) # 输出:2018
print(my_car.get_color()) # 输出:blue
print(my_car.get_mileage()) # 输出:15000
my_car.start_engine() # 输出:Starting engine...
my_car.drive(100) # 输出:Driving 100 miles...
print(my_car.get_mileage()) # 输出:15100
my_car.stop_engine() # 输出:Stopping engine...
```
阅读全文