class Car:
时间: 2024-06-19 14:00:16 浏览: 95
下面是一个简单的Python类示例,其中包含有关汽车的一些属性和方法:
```python
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
```
这个类将“制造商”、“型号”和“年份”作为传入的参数,并将它们存储在self对象中。它还定义了一个默认值为0的“里程表读数”,并包含了几个方法来访问和更新此值。
例如,你可以使用以下代码创建一个Car对象并访问其方法:
```python
my_car = Car('audi', 'a4', 2021)
print(my_car.get_descriptive_name()) # 输出:2021 Audi A4
my_car.update_odometer(100) # 设置里程表读数为100
my_car.read_odometer() # 输出:This car has 100 miles on it.
my_car.increment_odometer(50) # 增加里程表读数50
my_car.read_odometer() # 输出:This car has 150 miles on it.
```
阅读全文