简体   繁体   English

Python:如何递归地在打印中应用__str__

[英]Python: how to recursively apply __str__ in print

I had some problem printing user-defined class instance in containers. 在容器中打印用户定义的类实例时遇到一些问题。 In short, if my code is: 简而言之,如果我的代码是:

class A():
    def __str__(self):
        return 'abc'

class B():
    def __str__(self):
        return str(A())

a,b=A(),B()
C=[[a],b]
print(C)

Then the output should be like: [[<__main__.A object at 0x02D99910>], <__main__.B object at 0x02DD5030>] , but I want it to recursively apply customized __str__ and works even in nested lists or classes, ie I want the output to be [['abc'],'abc'] . 然后输出应该像这样: [[<__main__.A object at 0x02D99910>], <__main__.B object at 0x02DD5030>] ,但我希望它递归地应用自定义__str__ ,甚至在嵌套列表或类中都可以工作,即我想要输出为[['abc'],'abc'] Any pythonic way to do? 有什么pythonic的方法吗?

You would need to override the __str__ method of list , not A or B , since that's where the recursion needs to begin. 您将需要重写list__str__方法,而不是AB ,因为这是递归开始的地方。 That is, to turn a list into a string, you need to recursively turn each object in the list into a string. 也就是说,要将列表转换为字符串,您需要递归将列表中的每个对象转换为字符串。 Unfortunately, you cannot do that. 不幸的是,您不能那样做。 The best you can do is write a separate function, something like 最好的办法是编写一个单独的函数,例如

def list_to_str(l):
    if isinstance(l, list):
        return "[%s]" % (", ".join(map(list_to_str, l)),)
    else:
        return "'%s'" % (str(l),)

print(list_to_str(C))

@Blckknight should have submitted as an answer, because that seems to be the correct answer (it worked for my very similar question): @Blckknight应该已经提交了答案,因为这似乎是正确的答案(它适用于我非常相似的问题):

**override repr () instead of str () **改写repr ()代替str ()

def __repr__(self):
    return "abc"

you can also add this for completeness def str (self): return self. 您也可以为完整性def str (self)添加此函数:return self。 repr () 代表 ()

@Blckknight if you want to resubmit as an answer for the points, you should. @Blckknight如果您想重新提交积分的答案,则应该这样做。 I wish I could just add a comment but i don't have the reputation to do that. 我希望我可以添加评论,但我没有做到这一点的声誉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM