'numpy.ndarray'对象不可调用

时间:2014-12-31 01:22:57

标签: python callable multidimensional-array

请不要忽视长码,这很简单。 Basicaly我试图用Python做一个生命游戏。这是我收到错误的地方。

当我调用neighbour_count()函数时,我可以正确地获得每个元素所具有的邻居数。

def neighbours_count(self):

    neighbours_count = convolve2d(self.board, np.ones((3, 3)), 
                                  mode='same', boundary='wrap') - self.board                                      
    self.neighbours_count = neighbours_count   

然后我想进行下一步并采取行动,制定4条规则,游戏正确进行:

def make_step(self):
    # We want to check the actual board and not the board that exists after eg. step 2.
    self.board_new = np.zeros(shape=(self.size, self.size))

    # 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
    mask = (self.board == 1) & (self.neighbours_count < 2)
    self.board_new[mask] = 0

    # 2. Any live cell with two or three live neighbours lives on to the next generation.
    mask1 = (self.board == 1) & (self.neighbours_count == 2)
    self.board_new[mask1] = 1
    mask2 = (self.board == 1) & (self.neighbours_count == 3)
    self.board_new[mask2] = 1        

    # 3. Any live cell with more than three live neighbours dies, as if by overcrowding.
    mask = (self.board == 1) & (self.neighbours_count > 3)
    self.board_new[mask] = 0

    # 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
    mask = (self.board == 0) & (self.neighbours_count == 3)
    self.board_new[mask] = 1

    self.board = self.board_new

然而,当我想再做相同的事情(即计算邻居)时,我第二次调用neighbour_count函数:

  

TypeError:&#39; numpy.ndarray&#39;对象不可调用

我花了不合理的时间在这上面,有人可以帮忙吗?

感谢。

1 个答案:

答案 0 :(得分:3)

最初,neighbours_count是一种方法:

def neighbours_count(self):

    neighbours_count = convolve2d(self.board, np.ones((3, 3)), 
                                  mode='same', boundary='wrap') - self.board                                      
    self.neighbours_count = neighbours_count   
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

但是,您可以使用convolve2d函数的结果替换此标记行中的方法(您很容易将 称为neighbours_count),所以当你试着再次调用它,你没有得到方法,你得到了价值。这是ndarray,并且不可调用,因此:

TypeError: 'numpy.ndarray' object is not callable

我不确定你要做什么,但是如果你想在某处隐藏价值,人们通常会使用单个下划线,例如self._neighbours_count