【问题标题】:TypeError: 'function' object has no attribute '__getitem__' [closed]TypeError:'function'对象没有属性'__getitem__' [关闭]
【发布时间】:2012-11-28 04:28:25
【问题描述】:

在 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__'

请帮忙。

【问题讨论】:

  • 关于您的 numpy 代码的一些一般性评论:1) 尝试import numpy as np,因为这是 numpy 约定。 2)使用向量运算,即:a = b * l * p,而不是双循环。它会快数百或数千倍,并且更容易阅读。 3)不要将numpy数组索引为array[i][j],而是使用它array[i,j]它更快,写起来更短;)。总结一下,请阅读 numpy 教程。

标签: python arrays function


【解决方案1】:

您似乎忘记了一对括号:

a = makeGrid(dim)

你现在拥有的:

a = makeGrid

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

a[i]

它正在尝试对一个函数进行索引,该函数没有使用括号符号进行索引所需的 __getitem__ magic method

【讨论】:

    【解决方案2】:

    正如其他人所说,您需要正确调用 makeGrid.... 仅供参考,这是在 Python 中很常见的错误,通常意味着您的变量不是您认为的类型(在这种情况下,您期望的是一个矩阵,但得到了一个函数)

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

    【讨论】:

      【解决方案3】:

      您不是在调用makeGrid(),而是将函数对象本身分配给a

          a = makeGrid(dim) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-11
        • 1970-01-01
        • 2015-07-26
        • 2012-12-04
        • 2012-10-15
        • 2014-01-16
        • 2017-02-27
        • 2018-01-28
        相关资源
        最近更新 更多