You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类中添加自身实例到类列表触发AttributeError的问题

问题原因及解决方案

错误根源

你写的self.Player是试图访问当前实例的Player属性,但你的PLayer类并没有定义这个属性,自然会触发AttributeError。你真正想添加到列表里的是当前实例本身,应该直接用self代替self.Player。

另外,访问类属性时,更规范的方式是用类名(比如PLayer.TOTAL_PLAYER_LIST)而非self,避免实例意外覆盖类属性导致逻辑出错。

修正后的代码示例

class PLayer:
    # 类属性:存储所有玩家实例
    TOTAL_PLAYER_LIST = []

    def __init__(self, name):
        self.name = name
        # 将当前实例添加到类属性列表中
        PLayer.TOTAL_PLAYER_LIST.append(self)

验证示例

# 创建几个玩家实例
p1 = PLayer("Alice")
p2 = PLayer("Bob")

# 查看所有玩家实例
print(PLayer.TOTAL_PLAYER_LIST)
# 输出类似:[<__main__.PLayer object at 0x...>, <__main__.PLayer object at 0x...>]

内容的提问来源于stack exchange,提问作者Matteo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:40:42