python - 在Python中递归打印对象的所有属性、列表、字典等

标签 python python-2.7 object recursion

使用Python 2.7.10,我有这个脚本:

#!/usr/bin/python

#Do `sudo pip install boto3` first
import boto3
import json

def generate(key, value):
    """
    Creates a nicely formatted Key(Value) item for output
    """
    return '{}={}'.format(key, value)

def main():
    ec2 = boto3.resource('ec2', region_name="us-west-2")
    volumes = ec2.volumes.all()
    for vol in volumes:
        #print(vol.__str__())
        #print(vol.__dict__)
        print vol

     # vol object has many attributes, which can be another class object. 
     # For ex:
            #vol.volume_id),
            #vol.availability_zone),
            #vol.volume_type),

        # only process when there are tags to process
        # HERE: tags is another object which can contain a dict/list
        #if vol.tags:
        #    for _ in vol.tags:
        #        # Get all of the tags
        #        output_parts.extend([
        #            generate(_.get('Key'), _.get('Value')),
        #        ])


        # output everything at once.
        print ','.join(output_parts)

if __name__ == '__main__':
    main()

是否有一个函数可以使用一次调用递归地打印所有对象的属性?如何在一次调用中打印 val.xxxxx 和 val.tags.xxxx 的值。

我尝试使用 .__dict__.__str__() 打印对象,但没有帮助。

最佳答案

这是一个函数,您可以将其放入对象的 str 中。您也可以直接调用它,传入您想要打印的对象。该函数返回一个字符串,表示对象内容的格式良好的遍历。

感谢来自 forum.pythonistacafe.com 的 @ruud 提出了这个解决方案。

def obj_to_string(obj, extra='    '):
    return str(obj.__class__) + '\n' + '\n'.join(
        (extra + (str(item) + ' = ' +
                  (obj_to_string(obj.__dict__[item], extra + '    ') if hasattr(obj.__dict__[item], '__dict__') else str(
                      obj.__dict__[item])))
         for item in sorted(obj.__dict__)))


class A():
    def __init__(self):
        self.attr1 = 1
        self.attr2 = 2
        self.attr3 = 'three'


class B():
    def __init__(self):
        self.a = A()
        self.attr10 = 10
        self.attrx = 'x'


class C():
    def __init__(self):
        self.b = B()


class X():

    def __init__(self):
        self.abc = 'abc'
        self.attr12 = 12
        self.c = C()

    def __str__(self):
        return obj_to_string(self)


x = X()

print(x)

输出:

<class '__main__.X'>
    abc = abc
    attr12 = 12
    c = <class '__main__.C'>
        b = <class '__main__.B'>
            a = <class '__main__.A'>
                attr1 = 1
                attr2 = 2
                attr3 = three
            attr10 = 10
            attrx = x

关于python - 在Python中递归打印对象的所有属性、列表、字典等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43689114/

相关文章:

python - 如何删除通过 Appengine 中的 Key 属性连接的实体连接的所有实体

python - Ubuntu - 找不到适用于 python2 的 PySide 模块,但适用于 python3

python - 如果仅使用两个级别,Matplotlib 轮廓剖面线将不起作用

php - 如何在 PHP 中回显自定义对象?

java - 对象可以继承字符串表示吗?

python - 当 Python Watchdog 的目录发生任何变化时如何运行函数?

python - 如何有效地在 REST 序列化程序中找到相关字段的数据库?

python - 我正在寻找一个允许与 Web 应用程序紧密集成的消息传递平台(如 XMPP)

python virtualenv 没有使用正确版本的 python

javascript - 创建一个最喜欢的水果对象数组