python定义一个汽车类,有颜色,马力,型号等属性,以及一个move()方法,创建几个汽车品牌对象,然后编写程序输出这些对象的属性值,调用move()方法(使用init()方法完成属性赋值)
时间: 2024-04-30 10:18:39 浏览: 67
python中类的属性和方法介绍
下面是一个简单的 Python 代码,定义了一个汽车类,包括颜色、马力、型号等属性以及一个 move() 方法:
```python
class Car:
def __init__(self, color, horsepower, model):
self.color = color
self.horsepower = horsepower
self.model = model
def move(self):
print(f"The {self.color} {self.model} with {self.horsepower} horsepower is moving.")
```
接下来我们可以创建几个汽车品牌对象,然后输出它们的属性值并调用 move() 方法:
```python
car1 = Car("blue", 150, "BMW")
car2 = Car("red", 200, "Audi")
car3 = Car("black", 120, "Toyota")
print(f"car1 is a {car1.color} {car1.model} with {car1.horsepower} horsepower.")
car1.move()
print(f"car2 is a {car2.color} {car2.model} with {car2.horsepower} horsepower.")
car2.move()
print(f"car3 is a {car3.color} {car3.model} with {car3.horsepower} horsepower.")
car3.move()
```
输出结果如下:
```
car1 is a blue BMW with 150 horsepower.
The blue BMW with 150 horsepower is moving.
car2 is a red Audi with 200 horsepower.
The red Audi with 200 horsepower is moving.
car3 is a black Toyota with 120 horsepower.
The black Toyota with 120 horsepower is moving.
```
阅读全文