pta按要求编写一个类car
时间: 2024-09-17 11:01:04 浏览: 35
PTA 统计一个整数的位数
在Python中,我们可以创建一个名为`Car`的类,用于表示汽车的基本属性和行为。以下是一个简单的`Car`类的示例:
```python
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
self.speed = 0 # 初始速度
def start_engine(self):
print(f"{self.brand} {self.model} started.")
def accelerate(self, speed_increase):
if speed_increase > 0:
self.speed += speed_increase
print(f"{self.brand} {self.model} is now at {self.speed} km/h.")
else:
print("Invalid speed increase.")
def stop(self):
self.speed = 0
print(f"{self.brand} {self.model} stopped.")
# 示例如何使用Car类
my_car = Car('Toyota', 'Corolla', 2022)
my_car.start_engine()
my_car.accelerate(50)
my_car.stop()
阅读全文