创建任何对象的 map/contents

Creating a map/contents of any object

在Python 3.6。我想做的是创建一个可以接受任何对象然后生成树状内容的函数。

类似于一本书:

1. Object
 1.1 member: integer
 1.2 member: list
   2.1 list: element 1
   2.2 list: element 2
 1.3 member: string

我的目的是使用数字作为技术读数的关键,数字也可以代表比 id() 生成的更容易理解的 ID 号。因为我要处理的对象都是类型,所以我希望函数是递归的。这是我目前所拥有的:

def contents(a, n = 0, lim = 5, prefix=""):
    index = 1
    text = ""
    j = None
    if n < lim:
        try:
            for i in a.__dict__:
                text = text + "\n" + ("\t" *(n)) + prefix + str(index) + ", " + str(i) + ": " + contents(a.__dict__[i], n = n + 1, prefix=str(n)+".") + ""
                index += 1
        except:
            try:
                for i, j in a.items():
                    text = text + "\n" + ("\t"*(n)) + prefix + str(index) + ", " + str(i) + ": " + contents(i, n = n + 1, prefix=str(n)+".") + ""
                    index += 1
                except:
                    if isinstance(a, str):
                        text = text + "\n" + ("\t"*(n)) + prefix  + str(index) + ", " + str(a) + " "
                    else:
                        try:
                            for i in a:
                                text = text + "\n" + ("\t"*(n)) + prefix  + str(index) + ", " + str(i) + contents(i, n = n + 1, prefix=str(n)+".") + " "
                                index += 1

                    except:
                        text = text + "\n" + ("\t"*(n)) + prefix  + str(index) + ", " + str(a) + " "

    else:
        text = text + "limit. \n"
    return text 

a为对象,n为当前递归次数,lim为递归限制,前缀与显示的对象ID有关。

这里是测试对象

class Aclass:

    def __init__(self):
        self.a = [12, 24]
        self.b = 5

a = [Aclass(), 1, "2", 3, 4, Aclass(), {"c":"d","e":"f"}]

我 运行 遇到的问题与列表的奇怪递归行为有关,我已经对字符串进行了例外处理,因为该字符串将注册为由可迭代对象组成的可迭代对象,这将递归如果我没有设置限制,则无限期。现在,像 [1, 2, 3, 4] 这样的简单数字列表通常会将数字列出两次,就好像它分解为一个项目列表 [1] 然后报告里面的数字:1.

您应该看看 pprint 模块,它是标准发行版的一部分。它已经解决了这个问题,因此可以作为您的代码的基础。 (例如,我可以很容易地看到,通过 subclassing PrettyPrinter class 添加数字。)

此代码:

class Aclass:
    def __init__(self):
        self.a = [12, 24]
        self.b = 5

a = [Aclass(), 1, "2", 3, 4, Aclass(), {"c":"d","e":"f"}]

import pprint
s = pprint.pformat(a, indent=4)
print(s)

产生这个输出:

[   <__main__.Aclass object at 0x1060fb160>,
    1,
    '2',
    3,
    4,
    <__main__.Aclass object at 0x1060fb198>,
    {'c': 'd', 'e': 'f'}]