You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中打印嵌套对象的属性及对应值?

解决Python嵌套对象属性与值的打印问题

要实现打印嵌套对象的属性及对应值,你需要递归遍历嵌套对象的属性,而不是仅打印对象的内存地址。以下是修改后的代码:

class A:
    def __init__(self):
        self.a = 1
        self.b = 2


oba = A()


class MyClass:
    def __init__(self):
        self.prop1 = "value1"
        self.prop2 = "value2"
        self.obj = oba


def print_nested_attrs(obj):
    for attr in dir(obj):
        if not attr.startswith("__"):
            value = getattr(obj, attr)
            # 判断是否为自定义类实例(排除内置类型)
            if hasattr(value, '__dict__') and not isinstance(value, (str, int, float, list, dict, tuple, set)):
                nested_content = []
                # 收集嵌套对象的属性和值
                for nested_attr in dir(value):
                    if not nested_attr.startswith("__"):
                        nested_content.append(f"{nested_attr} {getattr(value, nested_attr)}")
                # 拼接嵌套内容后打印
                print(f"{attr} {'  '.join(nested_content)}")
            else:
                print(f"{attr} {value}")


obj = MyClass()
print_nested_attrs(obj)

代码说明

  • 遍历对象的非内置属性:用dir(obj)筛选出不以__开头的属性,排除Python内置的魔法属性。
  • 识别嵌套对象:通过hasattr(value, '__dict__')判断属性值是否为自定义类实例,同时排除字符串、数字、列表等内置类型,避免无意义的递归。
  • 拼接嵌套内容:遇到嵌套对象时,先收集其所有属性和对应值,再和外层属性名拼接后打印,符合你期望的输出格式。

输出结果

obj a 1  b 2
prop1 value1
prop2 value2

内容的提问来源于stack exchange,提问作者Ino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:53:29