问题描述
tldr;我正在尝试使用 __repr__()
和 pprint()
将自定义 python 类漂亮地打印到终端,但无论我传递给 pprint()
的宽度是多少,输出宽度都保持不变。我已经看到了问题 How can I make my class pretty printable in Python? - Stack Overflow,但它没有解释为什么 width 在我的情况下没有改变,即使 pprint() 成功打印了我的自定义类。
这是我的 __repr__()
函数。
def __repr__(self):
output = 'task(' + repr(self.name) + ',' + repr(self.subtasks) + ')'
return output
问题来了:当我尝试使用以下循环测试 pprint()
时,
for width in [ 80,20,5 ]:
print('WIDTH =',width)
pprint(task_tree,width=width)
所有输出都具有相同的宽度。
WIDTH = 80
task(root,[task(Top Level 1,[task(secondary,[]),task(secondary b,task(secondary c,[])]),task(Top Level 2,task(Top Level 3,[])])
WIDTH = 20
task(root,[])])
WIDTH = 5
task(root,[])])
可能出什么问题了?我应该如何修改我的类的 __repr__()
以使其按预期工作,即 pprint() 打印宽度为 80、20 和 5 个字符的类的表示?
我的方法基于 pprint — Pretty-Print Data Structures — PyMOTW 3 的以下摘录,其中演示了如何将 pprint()
用于任意类。
任意类
PrettyPrinter
使用的 pprint()
类也可以与自定义类一起使用,前提是它们定义了 __repr__()
方法。
pprint_arbitrary_object.py
from pprint import pprint
class node:
def __init__(self,name,contents=[]):
self.name = name
self.contents = contents[:]
def __repr__(self):
return (
'node(' + repr(self.name) + ',' +
repr(self.contents) + ')'
)
trees = [
node('node-1'),node('node-2',[node('node-2-1')]),node('node-3',[node('node-3-1')]),]
pprint(trees)
嵌套对象的表示由 PrettyPrinter
组合以返回完整的字符串表示。
$ python3 pprint_arbitrary_object.py
[node('node-1',[node('node-2-1',[node('node-3-1',[])])]
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)