如何让我的类在Python中可打印?

Pae*_*els 6 python formatting pretty-print python-3.x

Python有一个漂亮的打印机(pprint(...)).我想让我的课程相当可打印.如果我提供某个界面,那么漂亮的打印会以更好的方式打印我的实例吗?

8.11节中的Python文档显示了不同的示例,但没有示例如何使用户定义的类具有可打印性.

那么我的课程需要提供哪种界面?
还有其他(可能更好)的格式化程序吗?


使用案例:

我想打印ConfigParser的内容,为此我创建了一个名为ExtendenConfigParser的扩展版本.所以我可以添加更多功能或添加匹配的漂亮打印界面.

Mar*_*ers 7

pprint不寻找任何钩子.在pprint.PrettyPrinter使用派遣模式代替; 关于class.__repr__引用的类上的一系列方法.

您可以子类pprint.PrettyPrinter来教它关于您的类:

class YourPrettyPrinter(pprint.PrettyPrinter):
    _dispatch = pprint.PrettyPrinter.copy()

    def _pprint_yourtype(self, object, stream, indent, allowance, context, level):
        stream.write('YourType(')
        self._format(object.foo, stream, indent, allowance + 1,
                     context, level)
        self._format(object.bar, stream, indent, allowance + 1,
                     context, level)
        stream.write(')')

    _dispatch[YourType.__repr__] = _pprint_yourtype
Run Code Online (Sandbox Code Playgroud)

然后直接使用该类来打印包含YourType实例的数据.请注意,这取决于具有自己的自定义__repr__方法的类型!

您还可以将函数直接插入PrettyPrinter._dispatch字典中; self是明确传递的.这可能是第三方库的更好选择:

from pprint import PrettyPrinter

if isinstance(getattr(PrettyPrinter, '_dispatch'), dict):
     # assume the dispatch table method still works
     def pprint_ExtendedConfigParser(printer, object, stream, indent, allowance, context, level):
         # pretty print it!
     PrettyPrinter._dispactch[ExtendedConfigParser.__repr__] = pprint_ExtendedConfigParser
Run Code Online (Sandbox Code Playgroud)

有关如何编写其他分派方法的信息,请参阅pprint模块源代码.

与往常一样,单下划线名称_dispatch是可在未来版本中更改的内部实现细节.但是,这是您在这里的最佳选择.