相关疑难解决方法(0)

__str__和__repr__之间的区别?

之间有什么区别__str____repr____str__

python repr magic-methods

2545
推荐指数
21
解决办法
61万
查看次数

Python __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为此)?

python

103
推荐指数
3
解决办法
9万
查看次数

标签 统计

python ×2

magic-methods ×1

repr ×1