TypeError:'function'对象没有属性'__getitem__'

时间:2012-12-10 17:51:53

标签: python arrays function

在python中编写一些代码来评估基本函数。我有一个带有一些值的二维数组,我想将函数应用于每个值并得到一个新的二维数组:

import numpy as N
def makeGrid(dim):
    ''' Function to return a grid of distances from the centre of an array.
    This version uses loops to fill the array and is thus slow.'''
    tabx = N.arange(dim) - float(dim/2.0) + 0.5
    taby = N.arange(dim) - float(dim/2.0) + 0.5
    grid = N.zeros((dim,dim), dtype='float')
    for y in range(dim):
        for x in range(dim):
            grid[y,x] = N.sqrt(tabx[x]**2 + taby[y]**2)
    return grid

import math

def BigGrid(dim):
    l= float(raw_input('Enter a value for lambda: '))
    p= float(raw_input('Enter a value for phi: '))
    a = makeGrid 
    b= N.zeros ((10,10),dtype=float) #Create an array to take the returned values
    for i in range(10):
        for j in range (10):
            b[i][j] = a[i][j]*l*p
    return b


if __name__ == "__main__":
    ''' Module test code '''
    size = 10 #Dimension of the array
    newGrid = BigGrid(size)
    newGrid = N.round(newGrid, decimals=2)
    print newGrid

但我得到的只是错误信息

Traceback (most recent call last):
  File "sim.py", line 31, in <module>
    newGrid = BigGrid(size)
  File "sim.py", line 24, in BigGrid
    b[i][j] = a[i][j]*l*p
TypeError: 'function' object has no attribute '__getitem__'

请帮忙。

3 个答案:

答案 0 :(得分:26)

看来你忘记了一对括号:

a = makeGrid(dim)

你现在拥有什么:

a = makeGrid

只是对makeGrid函数进行别名而不是调用它。然后,当您尝试索引a时,如下所示:

a[i]

它正在尝试索引到一个函数,该函数没有使用括号表示法索引所需的__getitem__ magic method

答案 1 :(得分:4)

正如其他人所说,你需要正确地调用makeGrid ....就像fyi一样,这在Python中是一个相当常见的错误,它通常意味着你的变量不是你认为的类型(在这种情况下,你期待一个矩阵,但得到了一个函数)

TypeError: 'function' object has no attribute '__getitem__'

答案 2 :(得分:3)

您没有致电makeGrid(),而是将功能对象本身分配给a

    a = makeGrid(dim)