Python:lis的变量范围和封装

2024-09-30 07:30:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类图(简体):

from Enums import *
import Globals
import Tile

class Map:
    tiles = []  #the actual map, it's a 2D list of Tile objects
    for x in range(Globals.mapWidth):
        for y in range(Globals.mapHeight):
            self.tiles[x][y].addItem(Items.Foliage)

以及一个类瓷砖:

^{pr2}$

我的问题是类磁贴中的items[]数组似乎在类的每个实例中共享。例如,在For循环的末尾, 打印(长度(自身瓷砖[x] [y].项) 每一块砖返回25。为什么会这样?我应该有25个大小为1的列表,但是在循环中打印列表的大小从0增加到25。有人能解释一下这里发生了什么吗?非常感谢您的帮助:)


Tags: theinfromimportmap列表forrange
1条回答
网友
1楼 · 发布于 2024-09-30 07:30:11

您的items是一个类属性,这就是为什么它似乎在所有实例之间共享。在

class Tile:
    def __init__(self, type):
        self.items = []
        self.type = type

相关问题 更多 >

    热门问题