【问题标题】:Python Trouble with static class members in constructor构造函数中静态类成员的Python问题
【发布时间】: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

标签: python class static


【解决方案1】:

您仍然应该使用Player. 访问它们,即使它们是静态的并且是类的实例:

class Player:

    nPlayers = 0
    player_list = []

    def __init__ (self):
        self.n = Player.nPlayers + 1
        Player.nPlayers += 1
        Player.player_list.append(self)

【讨论】:

  • @Oryx 您可能希望将此作为已接受的答案。谢谢你。
猜你喜欢
  • 1970-01-01
  • 2013-01-16
  • 2017-04-04
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多