Dan*_*Dan 0 python formatting dictionary
我有一本字典和一条打印语句,如下所示:
d = {'ar':4, 'ma':4, 'family':pf.Normal()}
print(d)
Run Code Online (Sandbox Code Playgroud)
这给了我
{'ar': 4, 'ma': 4, 'family': <pyflux.families.normal.Normal object at 0x11b6bc198>}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以清理“family”键的值吗?重要的是,调用保持简单的“print(d)”,因为它用于打印其他字典而不会出现此问题。这可能吗?谢谢你的时间。
编辑:
感谢您的回答,我会将其标记为正确,但我还没有尝试过,无法确认。我最终创建了另一个字典,其中清理后的字符串作为键,对象作为值。这需要更多的工作,但我在阅读/得到回复之前就完成了,所以我坚持了下来。还是谢谢了!
你误会了。您不想更改print(dict)输出。这需要改变内置词典的打印方式。您想要__repr__()向您的pf.Normal()对象添加自定义。
我相信pf.Normal()来自pyfluxpackage,所以我建议查看该类应该保存哪些数据,并通过从该类继承来漂亮地打印它:
class CustomNormalObject(pf.Normal):
def __repr__(self):
# Add pretty printed data here
pass
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要将自己的参数传递到自定义类中,您可以使用super():
class CustomNormalObject(pf.Normal):
def __init__(self, myparm, *args, **kwargs):
# If using Python 3, you can call super without
# passing in any arguments. This is simply for Python 2
# compatibility.
super(CustomNormalObject, self).__init__(*args, **kwargs)
self.myparm = myparm
def __repr__(self):
# Add pretty printed data here
pass
Run Code Online (Sandbox Code Playgroud)