[英]__str__ method not working when objects are inside a list or dict
In this example, the first print statement outputs the string returned by ball.__str__()
, while the other two do not: 在这个例子中,第一个print语句输出ball.__str__()
返回的字符串,而其他两个不输出:
class Ball:
def __init__(self, parent, xpos = 50, ypos = 50, radius = 100, vx = 0, vy = 0, mass = 1):
"""
x,y are positions
vx and vy are velocities in cells/second
"""
self.x = xpos
self.y = ypos
self.r = radius
self.vx = vx
self.vy = vy
self.mass = mass
self.board = parent
def __str__(self):
return "Ball: x={0}, y={1}, r={2}, vx={3}, vy={4}".format(self.x,self.y,self.r,self.vx,self.vy)
class Board:
def __init__(self, width = 100, height = 100, sps = 2):
pass
board = Board()
ball = Ball(board)
ball_list = [Ball(board), Ball(board)]
ball_dict = {'ball_1':Ball(board), 'ball_2':Ball(board)}
print(ball)
print(ball_list)
print(ball_dict)
output: 输出:
Ball: x=50, y=50, r=100, vx=0, vy=0
[<__main__.Ball object at 0x106f79f98>, <__main__.Ball object at 0x106f79fd0>]
{'ball_1': <__main__.Ball object at 0x106f81048>, 'ball_2': <__main__.Ball object at 0x106f81080>}
Questions: 问题:
print
uses the __str__
method, but printing a dict
or list
invokes dict.__str__
/ list.__str__
respectively, which use the __repr__
method to serialise contained items. print
使用__str__
方法,但打印dict
或list
调用dict.__str__
/ list.__str__
,它们使用__repr__
方法序列化包含的项目。 Define __repr__
on your class to mimic __str__
. 在类上定义__repr__
以模仿__str__
。 Eg this will do: 例如,这将做:
class Ball:
...
def __str__(self):
...
__repr__ = __str__
Note that __repr__
should return a representation which preferably is valid Python code, like Ball(Board(100, 100, 2))
. 请注意, __repr__
应该返回一个表示,最好是有效的Python代码,如Ball(Board(100, 100, 2))
__repr__
Ball(Board(100, 100, 2))
。
An example should help. 一个例子应该有帮助。
class Foo():
def __str__(self):
return '__str__'
def __repr__(self):
return '__repr__'
x = Foo(); print(x)
__str__
lst = [Foo(), Foo(), Foo()]
print(lst)
[__repr__, __repr__, __repr__]
Inside a data structure, the __repr__
method is called, not the __str__
. 在数据结构内部,调用__repr__
方法,而不是__str__
。 If you have none such method defined, python falls back on the default __repr__
that object
provides. 如果没有定义这样的方法,python会回__repr__
object
提供的默认__repr__
。
As mentioned, the fix is to define a __repr__
method and have it refer to the currently defined __str__
method of your class. 如上所述,修复方法是定义一个__repr__
方法,并让它引用您当前定义的类的__str__
方法。
You could also monkeypatch the method on after the class definition, like this: 你也可以在类定义之后monkeypatch方法,如下所示:
Foo.__repr__ = Foo.__str__
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.