python __str__用于对象

python __str__用于对象,第1张

python __str__用于对象

您需要将要打印的项目子类化。

from itertools import chainclass PrintableList(list): # for a list of dicts    def __str__(self):        return '. '.join(' '.join(str(x) for x in chain.from_iterable(zip((item[0], 'is', 'and'), item[1])))     for item in (item.items()[0] for item in self)) + '.'class PrintableDict(dict): # for a dict    def __str__(self):        return '. '.join(' '.join(str(x) for x in chain.from_iterable(zip((item[0], 'is', 'and'), item[1])))     for item in self.iteritems()) + '.'class Foo:   def __init__(self):      self.d = PrintableDict({"Susan": ("Boyle", 50, "alive"),         "Albert": ("Speer", 106, "dead")})class Bar:   def __init__(self):      self.l = PrintableList([{"Susan": ("Boyle", 50, "alive")},         {"Albert": ("Speer", 106, "dead")}])foo = Foo()print self.dbar = Bar()print self.l


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5662898.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存