简单的python类
时间: 2023-06-30 07:04:22 浏览: 31
下面是一个简单的 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_description(self):
return f"{self.year} {self.make} {self.model}"
def read_odometer(self):
return f"This car has {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
car = Car("Toyota", "Camry", 2020)
print(car.get_description())
car.update_odometer(5000)
print(car.read_odometer())
car.increment_odometer(100)
print(car.read_odometer())
```
这个类表示一个汽车,具有以下属性和方法:
- `make`、`model`和`year`是汽车的属性。
- `odometer_reading`是记录汽车里程数的属性。
- `get_description()`方法返回汽车的描述。
- `read_odometer()`方法返回汽车的里程数。
- `update_odometer(mileage)`方法用于更新里程数,但是不允许回滚。
- `increment_odometer(miles)`方法用于增加里程数。
通过创建一个 `Car` 对象,我们可以调用这些方法并获取汽车的属性和状态。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)