之间有什么区别__str__和__repr__在__str__?
在Java中,如果我调用List.toString(),它将自动调用List内每个对象的toString()方法.例如,如果我的列表包含对象o1,o2和o3,则list.toString()将如下所示:
"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"
Run Code Online (Sandbox Code Playgroud)
有没有办法在Python中获得类似的行为?我在我的类中实现了__str __()方法,但是当我打印出一个对象列表时,使用:
print 'my list is %s'%(list)
Run Code Online (Sandbox Code Playgroud)
它看起来像这样:
[<__main__.cell instance at 0x2a955e95f0>, <__main__.cell instance at 0x2a955e9638>, <__main__.cell instance at 0x2a955e9680>]
Run Code Online (Sandbox Code Playgroud)
如何让python自动为列表中的每个元素调用我的__str__(或者dict为此)?