簡體   English   中英

當對象在列表或字典中時__str__方法不起作用

[英]__str__ method not working when objects are inside a list or dict

在這個例子中,第一個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)

輸出:

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>}

問題:

  1. 為什么python會以這種方式運行?
  2. 如何讓str字符串出現在列表和字典中?

print使用__str__方法,但打印dictlist調用dict.__str__ / list.__str__ ,它們使用__repr__方法序列化包含的項目。 在類上定義__repr__以模仿__str__ 例如,這將做:

class Ball:
    ...

    def __str__(self):
        ...

    __repr__ = __str__

請注意, __repr__ 應該返回一個表示,最好是有效的Python代碼,如Ball(Board(100, 100, 2)) __repr__ Ball(Board(100, 100, 2))

一個例子應該有幫助。

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__]

在數據結構內部,調用__repr__方法,而不是__str__ 如果沒有定義這樣的方法,python會回__repr__ object提供的默認__repr__

如上所述,修復方法是定義一個__repr__方法,並讓它引用您當前定義的類的__str__方法。

你也可以在類定義之后monkeypatch方法,如下所示:

Foo.__repr__ = Foo.__str__

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM