如何使我的班级在Python中可打印? [英] How can I make my class pretty printable in Python?

查看:38
本文介绍了如何使我的班级在Python中可打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Python has a pretty printer (pprint(...)). I would like to make my classes pretty printable. Will pretty print print my instances in a better way, if I provide a certain interface?

8.11 部分中的Python文档显示了不同的示例,但没有示例使用户定义的类可打印.

The Python documentation in section 8.11 shows different examples, but no example how to make a user defined class pretty printable.

那我的课程需要提供什么接口?
还有其他(也许更好)的格式化程序吗?

So what interface need my classes to provide?
Is there any other (maybe better) formatter?

用例:

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

I want to pretty print the content of ConfigParser, for which I have create an extended version called ExtendenConfigParser. So I have the possibility to add more functionality or add a matching pretty print interface.

推荐答案

pprint 不查找任何钩子. pprint.PrettyPrinter 使用调度模式代替;该类上的一系列方法,这些方法以 class .__ repr __ 引用为键.

pprint does not look for any hooks. The pprint.PrettyPrinter uses a dispatch pattern instead; a series of methods on the class that are keyed on class.__repr__ references.

您可以将 pprint.PrettyPrinter 子类化,以教授有关您的班级的信息:

You can subclass pprint.PrettyPrinter to teach it about your class:

class YourPrettyPrinter(pprint.PrettyPrinter):
    _dispatch = pprint.PrettyPrinter._dispatch.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

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

then use the class directly to pretty print data containing YourType instances. Note that this is contingent on the type having their own custom __repr__ method!

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

You can also plug functions directly into the PrettyPrinter._dispatch dictionary; self is passed in explicitly. This is probably the better option for a 3rd-party library:

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

请参见 pprint 模块源代码了解其他调度方法的编写方式.

See the pprint module source code for how the other dispatch methods are written.

与往常一样,单下划线名称(如 _dispatch )是内部实现的详细信息,可以在以后的版本中进行更改.但是,这是您在这里的最佳选择.分配表是在 Python 3.5 中添加的,并且至少存在于Python 3.5-3.9中阿尔法.

As always, single-underscore names like _dispatch are internal implementation details that can be altered in a future version. However, it is the best option you have here. The dispatch table was added in Python 3.5 and is present in at least Python 3.5 - 3.9 alpha.

这篇关于如何使我的班级在Python中可打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆