【问题标题】:Python 'builtin_function_or_method' object has no attribute '__getitem__' on list of listsPython 'builtin_function_or_method' 对象在列表列表中没有属性 '__getitem__'
【发布时间】:2017-06-29 07:51:27
【问题描述】:

通常此错误意味着括号存在问题(例如使用括号、缺少、错误的位置等),但这似乎不是问题所在。

#iterate through all the tiles on the map and set as a background color
for y in range(MAP_WIDTH):
    for x in range(MAP_HEIGHT):
        #checks if the tile is a wall
        wall = map[x][y].block_sight
        if wall:
            rlib.console_set_char_background(
            con, x, y, color_dark_wall, rlib.BKGND_SET)
        else:
            rlib.console_set_char_background(
            con, x, y, color_dark_ground, rlib.BKGND_SET)

错误发生在 wall = map 行中。该映射是一个列表列表,用于模拟 python 中数组的功能。 block_sight 为真或假,并在此处设置:

class Tile:
    #Tiles are components of the map
    def __init__(self, blocked, block_sight = None):
        #takes the information and stores it on the tile
        self.blocked = blocked

        #if not specified, block_sight if the same as blocked
        if block_sight is None: block_sight = blocked
        self.block_sight = block_sight

对此的任何帮助将不胜感激。

编辑:这是地图的构造方式:

#generates a list of lists with empty tiles as elements
def makemap():
    map = [[Tile(False) #Must call a conctructor, not a variable such as floor
        for y in range(MAP_HEIGHT)] #uses comprehension to generate lists
            for x in range(MAP_WIDTH)]

    #place two pillars to test the map
    map[30][22].blocked = True
    map[30][22].block_sight = True
    map[50][22].blocked = True
    map[50][22].block_sight = True

【问题讨论】:

  • 从错误看来,您的列表确实不是您所期望的。也许外部列表包含内置函数而不是内部列表。你能展示一下你是如何创建map的吗?
  • 你能在打电话之前把它打印出来map[x][y]看看你得到了什么吗?
  • 或者map 是您在函数式编程中使用的内置函数,而不是您的列表列表有其他名称?

标签: python-2.7


【解决方案1】:

在函数 makemap() 中,我忘记使用 map 作为全局变量,因此任何需要使用此函数构建的 map 的东西都无法访问它。添加“全局地图”作为函数的第一行解决了错误。

【讨论】:

    猜你喜欢
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2019-07-11
    • 2014-07-03
    • 1970-01-01
    相关资源
    最近更新 更多