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

Aru*_*gal 3 python recursion object python-2.7

使用 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()
Run Code Online (Sandbox Code Playgroud)

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

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

Mik*_*eyB 7

这是一个函数,您可以将其放入对象的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)
Run Code Online (Sandbox Code Playgroud)

输出:

<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
Run Code Online (Sandbox Code Playgroud)