python中创建子类Land_Rover,使用构造方法创建对象,设置品牌、颜色两个父类参数和两个自带参数,在子类中调用父类构造方法,调用子类,,创建对象并命名,访问对象属性,调用迭代函数,并输出结果
时间: 2024-02-29 12:52:33 浏览: 163
下面是基于您的要求编写的 Python 代码:
```python
# 定义汽车类
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
def __str__(self):
return f"{self.color} {self.brand} Car"
# 定义Land_Rover子类
class Land_Rover(Car):
def __init__(self, brand, color, model, year):
super().__init__(brand, color)
self.model = model
self.year = year
def __str__(self):
return f"{self.color} {self.brand} {self.model} ({self.year})"
# 创建Land_Rover对象
my_car = Land_Rover("Land Rover", "Silver", "Discovery", 2021)
# 访问对象属性
print(my_car.brand)
print(my_car.color)
print(my_car.model)
print(my_car.year)
# 调用迭代函数并输出结果
for attr, value in my_car.__dict__.items():
print(f"{attr}: {value}")
```
输出结果如下:
```
Land Rover
Silver
Discovery
2021
brand: Land Rover
color: Silver
model: Discovery
year: 2021
```
阅读全文