Jakub Kubis
Jakub Kubis

Reputation: 3

'numpy.ndarray' object is not callable

Please don't disregard the long code, it is really simple. Basicaly I am trying to do a Game of Life in Python. Here is where I get the error.

When I call the neighbour_count() function I can correctly get the number of neighbours that each element have.

def neighbours_count(self):

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

Then I want to make the next step and act on 4 rules, which it does and the game advances correctly:

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

However, when I want to DO THE SAME THING AGAIN (i.e. count the neighbours), then the second time I call the neighbour_count function I get:

TypeError: 'numpy.ndarray' object is not callable

I have spent unreasonable amount of time on this, can anyone help please?

Thanks.

Upvotes: 0

Views: 6935

Answers (1)

DSM
DSM

Reputation: 352959

Originally, neighbours_count is a method:

def neighbours_count(self):

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

But then you replace this method in the marked line by the result of the convolve2d function (which you've confusingly also called neighbours_count), so when you try to call it again, you don't get the method, you get the value. This is an ndarray, and it's not callable, and so:

TypeError: 'numpy.ndarray' object is not callable

I'm not sure what you're trying to do, but if you want to stash a value somewhere, people often use a single underscore, e.g. self._neighbours_count.

Upvotes: 3

Related Questions