python - 自定义数组类中 python/pygame 中运算符重载的一些问题

标签 python operator-overloading pygame typeerror

您好,感谢您查看此问题。对于我正在制作的基于图 block 的基本游戏,我制作了自己的容器类,其中包含代表世界地图的项目/值矩阵。为此,我学习了运算符重载。在大多数情况下,一切似乎都很好,但我得到的一些结果让我感到困惑。

class mapArray(object):

    def __init__(self, mapdata = None, (width,height) = None, fillnumber = 0):
        #If you are already given a map array, then you can just provide
        # that first, otherwise leave it as none. Fill number is used to change the entire 
        # map array so that the map will be a different tile type. 0 is most likely just grass.
        print "horses"
        if (mapdata == None) and (width, height) == None:
            self.mapdata = []

        elif mapdata is not None:
            self.mapdata = mapdata

        elif (width,height) is not None:
            self.mapdata = [[fillnumber] * width] * height

    def __setitem__(self, (x,y), value):
        #Allows you to assign values more intuitively with the array
        self.mapdata[y][x] = value

    def __getitem__(self, (x,y)):
        #Just reverses it so it works intuitively and the array is 
        # indexed simply like map[x,y] instead of map[y][x]
        return mapArray(self.mapdata[y][x])

    def __str__(self):
        return str(self.mapdata)

    def __repr__(self):
        return str(self.mapdata)

    def __len__(self):
        return len(self.mapdata)

getitem 工作正常。我将构造函数设置为接受给定的列表列表,或者提供仅生成该大小的数组的长度和宽度。以下是我为数组提供大小(而不是为其提供自己的值)时得到的结果。

testlist1 = mapArray(None, (3,3), 4)
print testlist1
testlist1[0,1] = 5
print testlist1

这给了我这些结果:

[[4,4,4],[4,4,4],[4,4,4]]
[[5,4,4],[5,4,4],[5,4,4]]

第一个结果是有道理的,但第二个结果似乎表明我覆盖的 setitem 方法存在问题。为什么它会替换每个列表的第一个索引?

同样令我困惑的是,当我提供自己的列表列表来替换 mapdata 参数时会发生什么。

randommap = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
testlist2 = mapArray(randommap)
print testlist2

该代码给了我这个类型错误:

def __init__(self, mapdata = None, (width,height) = None, fillnumber = 0):
TypeError: 'NoneType' object is not iterable

对我来说,这似乎是在说,本地图数据设置为 None 时,它​​是不可迭代的,但是我提供的随机 map 列表不应该替换 map 数据吗?也许我设置的条件语句有问题,因此它永远不会被替换。我似乎无法缩小问题的范围。任何帮助将不胜感激!

我是运算符重载的新手,因此如果有任何更有效的方法可以做到这一点,请告诉我。我知道 numpy 的存在可以为我完成大部分工作,但我想自己完成。 再次感谢! 瑞安

最佳答案

问题出在__init__()中。具体来说这一行:

self.mapdata = [[fillnumber] * width] * height

这将创建对同一列表的height引用。修复方法是:

self.mapdata = [[fillnumber] * width for x in xrange(height)]

关于python - 自定义数组类中 python/pygame 中运算符重载的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11895291/

相关文章:

python - 如何在 Python 中使用带前缀的 str.get_dummies?

python - 为什么必须将 "exec"(而不是 "eval")用于 Python 导入语句?

go - Go不支持运算符重载,但是我该如何解释时间包

c++ - 重载运算符 *

python - 怎样才能让 Action 更顺畅呢?

python - 在 python 中重新打开声音文件时出错

python - 需要计算时间戳之间的时间差并将其存储在变量中

python - 如何将数据帧转换为所需的格式?

c++ - 为什么删除 Actor 指针会导致 "Program.exe has triggered a breakpoint"

python - 列表中敌人之间的 Pygame/Python 测试?