【问题标题】:Calling list.index(a) results in attribute call, not method?调用 list.index(a) 会导致属性调用,而不是方法?
【发布时间】:2015-09-16 12:09:26
【问题描述】:

我一直在尝试创建一个脚本,该脚本在字典中获取列表,并对其进行编辑以创建类似网格的东西。我正在尝试使变量等效于列表中值的索引,但错误表明数据中没有这样的属性。我正在尝试调用 METHOD,而不是检索属性,但这就是机器认为我想要做的。

我使用的是 Python 3.5 的 32 位版本。

这是脚本。我已在相关行中添加了评论。

#Map Generation Script
GRID = {
1 : [1,1,1,1,1,1,1,1,1,1],
2 : [1,1,1,1,1,1,1,1,1,1],
3 : [1,1,1,1,1,1,1,1,1,1],
4 : [1,1,1,1,1,1,1,1,1,1],
5 : [1,1,1,1,1,1,1,1,1,1],
6 : [1,1,1,1,1,1,1,1,1,1],
7 : [1,1,1,1,1,1,1,1,1,1],
8 : [1,1,1,1,1,1,1,1,1,1],
9 : [1,1,1,1,1,1,1,1,1,1],
10 : [1,1,1,1,1,1,1,1,1,1]
}

def usepen(x):
Areaedit = GRID[godpenx]
Areaedit[godpeny] = x
GRID[godpenx] = Areaedit

def makeshapeline(tile, length):
for item in GRID:               #I know this isn't indented properly
    for unit in GRID[item]:
        if unit == tile:
            locpenx = GRID.index(item) #offending line
            locpeny = GRID[item].index(tile) 
            anglea = randrange(0,1)
            angleb = randrange(0,1)
            while anglea + angleb == 0:
                anglea = randrange(0,1)
                angleb = randrange(0,1)
            for nump in length:
                locpenx += anglea
                locpeny += angleb
                if locpenx or locpeny > 9:
                    break
                GRID[locpenx[locpeny]] = tile

usepen(0)
makeshapeline(0, randrange(1,8))
for item in GRID:
    print (GRID[item])

【问题讨论】:

  • 请注意,方法调用实际上只是获取然后调用可调用属性,并带有一些有趣的实例绑定内容。如果您收到AttributeError,那么您正试图在不是列表的东西上调用index

标签: python python-3.x methods python-3.5


【解决方案1】:

确实locpenx = GRID.index(item) 是违规行:

你需要有这样的东西-

locpenx = GRID[1].index(item) 

locpenx = GRID[2].index(item) 

.. 等等。

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多