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

如何将所有items类的实例自动添加到列表 无需手动逐个加入

你可以通过给items类添加类属性存储所有实例的方式实现自动收集,全程不需要手动修改itemsList,新增实例时会自动加入列表:

步骤1:修改items类代码

class items:
    # 新增类属性,所有items实例共享这个列表
    all_items = []
    def __init__(self, colour, name, ID, xpos, ypos):
        self.width = 20
        self.height = 20
        self.colour = colour
        self.name = name
        self.ID = ID
        self.xpos = xpos
        self.ypos = ypos
        # 实例初始化完成后自动加入列表
        items.all_items.append(self)

步骤2:直接获取所有实例列表

你原有创建实例的代码不需要做任何修改,创建完所有实例后直接赋值即可:

flower = items(red, "flower", "0001",xpositions[0] ,ypositions[0])
wood = items(brown, "wood", "0002",xpositions[1] ,ypositions[1])
iron = items(iron, "iron", "0003",xpositions[2] ,ypositions[2])
sticks = items(brown, "sticks", "0004",xpositions[3] ,ypositions[3])

# 按实例创建顺序生成的列表,和你想要的效果完全一致
itemsList = items.all_items

注意事项

如果后续有删除实例的需求,要同步把实例从items.all_items列表中移除,避免列表的引用导致实例无法被垃圾回收占用内存。如果需要itemsList不随后续新增的实例变动,可以改成浅拷贝:

itemsList = items.all_items.copy()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:45:03