在Python中以递归方式打印对象的所有属性,列表,字符串等

时间:2017-04-28 21:26:16

标签: 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__()打印对象,但没有帮助。

1 个答案:

答案 0 :(得分:1)

这是您可以放入对象的 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