Python pretty-print 嵌套对象

标签 python pretty-print

我有 3 个 Python 类 A、B 和 C。A 包含 B 对象,B 包含 C 的对象。我想要的是当我打印 A 类对象时,它应该以下面的格式漂亮地打印。 C类内部也可以有更多的嵌套。

A:
    loc : XYZ
    qual : ABC
    b :
        name : ABC
        age : 30
        c :
            address : ABC
            phn : 99009

以下是供引用的类。

class C(object):
    def __init__(self):
        self.address='ABC'
        self.phn=99009

class B(object):
    def __init__(self):
        self.name='ABC'
        self.age=30
        self.c = C()

class A(object):
    def __init__(self):
        self.loc = 'XYZ'
        self.qual = 'ABC'
        self.b = B()

最佳答案

下面的工作是让您的类继承自实现 __str__ 的公共(public)基类。方法:

class PrettyPrinter(object):
    def __str__(self):
        lines = [self.__class__.__name__ + ':']
        for key, val in vars(self).items():
            lines += '{}: {}'.format(key, val).split('\n')
        return '\n    '.join(lines)

class C(PrettyPrinter):
    def __init__(self):
        self.address='ABC'
        self.phn=99009

class B(PrettyPrinter):
    def __init__(self):
        self.name='ABC'
        self.age=30
        self.c = C()

class A(PrettyPrinter):
    def __init__(self):
        self.loc = 'XYZ'
        self.qual = 'ABC'
        self.b = B()

a = A()
print(a)

在 Python 3.6 和更新版本中,这显示为

A:
    loc: XYZ
    qual: ABC
    b: B:
        name: ABC
        age: 30
        c: C:
            address: ABC
            phn: 99009

请注意,所有属性都是自动打印的。它们的打印顺序由 vars 函数决定,该函数实际上在 __dict__ 字典中查找。该字典在 Python 3.5 及以下版本中具有不确定的顺序,因此打印输出不如 3.6 及更高版本。

关于Python pretty-print 嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51753937/

相关文章:

python - 找出所有可能的二进制组合

json - 在 HttpConfiguration 实例中的 ASP.NET Web API 应用程序中处理 json pretty-print 参数

python - 从单独的类访问 Tkinter Canvas

python - 使用 Pyo 在 Python 中播放声音

python - 如何以 json 格式(双引号) pretty-print (人类可读打印)Python dict?

将数字四舍五入到前 3 位数字(以数字开头!= 0)

python - 实现自定义 pretty-print 的最佳方法

python - Bottle 的 jsonify/pretty-print JSON

python - 如何用python替换字符串中的html元素?

python - Pandas DataFrame 提取所有列