【发布时间】:2020-09-02 05:52:12
【问题描述】:
我正在尝试编写游戏,并为 Player 创建了一个类。我想保留玩家的数量,以及作为类的静态成员存储的玩家列表,所以我在构造函数之外声明了它们。在构造函数中,我添加了代码来增加玩家数量并将新玩家添加到列表中。
class Player:
nPlayers = 0
player_list = []
def __init__ (self):
self.n = nPlayers + 1
nPlayers += 1
player_list += self
当我尝试使用构造函数创建新对象时,出现以下错误:
UnboundLocalError: local variable 'nPlayers' referenced before assignment
我该如何解决这个问题,以便我可以拥有这样的静态变量功能?
【问题讨论】:
-
顺便说一句,你真的应该阅读this