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

Python Field类邻域分配异常:所有实例共享邻居列表求助

问题分析与解决

嘿,这个问题的核心原因一眼就能看出来——你踩了Python类属性和实例属性的坑!

问题拆解

先看你定义的Field类:

class Field:
    posx = 0
    posy = 0
    used = False
    letter = ''
    neighbours = []  # 这里是类属性,所有实例共享同一个列表
    def __init__(self, x, y):
        self.posx = x
        self.posy = y

在Python里,直接写在类体里的变量属于类属性,是整个类共享的资源。也就是说你创建的4个Field对象,它们的neighbours其实指向同一个列表。

当你循环调用addNeighbour时,每次都是往这个共享列表里加元素:2x2表格里每个Field会添加3个邻居,4个实例总共加了4*3=12次,所以最后所有实例的neighbours列表都有12个元素。

修复方案

把neighbours改成实例属性,也就是移到__init__方法里初始化,让每个Field实例拥有自己独立的邻居列表:

class Field:
    posx = 0
    posy = 0
    used = False
    letter = ''
    def __init__(self, x, y):
        self.posx = x
        self.posy = y
        self.neighbours = []  # 每个实例都有专属的空列表
    def addNeighbour(self,neighbour):
        self.neighbours.append(neighbour)

修改后再运行代码,每个Field实例就会正确拥有3个邻居了。

额外小建议

其实posx、posy这类属性也可以直接在__init__里定义,不用先在类体里声明默认值,代码会更清晰:

class Field:
    def __init__(self, x, y):
        self.posx = x
        self.posy = y
        self.used = False
        self.letter = ''
        self.neighbours = []
    def addNeighbour(self,neighbour):
        self.neighbours.append(neighbour)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:46:58