【发布时间】:2022-01-13 00:22:15
【问题描述】:
我的代码没有按预期工作。我的部分代码如下所示:
lst_of_players = []
class Player:
def __init__(self, username):
self.username = username
self.level = 1
lst_of_players.append(self)
def level_up(self):
self.level += 1
player1 = Player("Player 1")
player2 = Player("Player 2")
player3 = Player("Player 3")
def level_up_all_players():
map(lambda player: player.level_up(), lst_of_players)
当我调用 level_up_all_players 函数时,我以为玩家的等级会提升 1,但事实并非如此。 当我打印玩家的等级时,他们仍然是调用函数之前的等级。
【问题讨论】:
-
您还应该将每个玩家添加到您的
lst_of_players;就目前而言,您的最小示例将不起作用,因为列表中没有任何内容。我认为这是需要调用地图的一个附带问题(因为它是延迟加载的)。
标签: python dictionary lambda