paython 创建Car类,自定义类的属性和方法,利用构造器创建对象,分别创建有参数的对象和无参数的对象,利用创建的对象去访问相关的属性和方法。
时间: 2024-06-13 20:04:14 浏览: 18
Car类是一个自定义的类,可以包含属性和方法。我们可以通过构造器来创建对象,对象可以访问类的属性和方法。下面是一个例子:
```
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def start(self):
print("The car is starting.")
def stop(self):
print("The car is stopping.")
# 创建有参数的对象
car1 = Car("Toyota", "Camry", 2020)
print(car1.brand) # 输出 Toyota
print(car1.model) # 输出 Camry
print(car1.year) # 输出 2020
car1.start() # 输出 The car is starting.
car1.stop() # 输出 The car is stopping.
# 创建无参数的对象
car2 = Car("", "", 0)
car2.brand = "Honda"
car2.model = "Civic"
car2.year = 2019
print(car2.brand) # 输出 Honda
print(car2.model) # 输出 Civic
print(car2.year) # 输出 2019
car2.start() # 输出 The car is starting.
car2.stop() # 输出 The car is stopping.
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)