输出复杂对象中的所有属性和属性名
时间: 2024-04-13 13:30:41 浏览: 26
好的,以下是一个示例代码,可以输出复杂对象中的所有属性和属性名:
```python
def print_attributes(obj, prefix=''):
if isinstance(obj, dict):
for key, value in obj.items():
if isinstance(value, (list, dict)):
print_attributes(value, prefix + key + '.')
else:
print(f"{prefix}{key}: {value}")
elif isinstance(obj, list):
for index, item in enumerate(obj):
if isinstance(item, (list, dict)):
print_attributes(item, prefix + str(index) + '.')
else:
print(f"{prefix}{index}: {item}")
else:
print(f"{prefix}: {obj}")
# 示例对象
complex_obj = {
'name': 'John',
'age': 25,
'address': {
'street': '123 Main St',
'city': 'New York',
'country': 'USA'
},
'hobbies': ['reading', 'painting', 'coding']
}
# 输出属性和属性名
print_attributes(complex_obj)
```
这段代码定义了一个递归函数 `print_attributes`,该函数会遍历复杂对象的属性,并输出属性名和对应的值。如果属性值仍然是复杂对象,则会递归调用该函数进行深度遍历。你可以根据需要自行调整输出格式或添加其他处理逻辑。希望这个示例能对你有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)