TKP
TKP

Reputation: 453

python int object is not callable?

Relatively new to Python. I'm trying to practice linked list but I'm stuck with an error and couldn't figure out what the issue is.

The error:

    self.assertEqual(l.size(), 1)
    TypeError: 'int' object is not callable

The code:

from node import Node

class List:
    def __init__(self):
        self.head = None
        self.size = 0

    def add(self, item):
        temp = Node(item)
        temp.setNext(self.head)    # ERROR ON THIS LINE
        self.head = temp
        size += 1

    def size(self):
        return self.size

    ...

Node:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

    ....

Test:

import unittest
import unorderedlist

class TestUnorderedList(unittest.TestCase):
    def test_add(self):
        l = unorderedlist.List()
        l.add(8)
        self.assertEqual(l.size(), 1)

if __name__ == '__main__':
    unittest.main()

It's funny because if I rename the size() to len and call it like l.len() it works fine. Anyone have a clue?

Upvotes: 0

Views: 506

Answers (2)

tuxtimo
tuxtimo

Reputation: 2790

You have hidden your method with the attribute. In your code you are then accessing the attribute which is of type int and so not callable. Avoid to name methods and attributes the same.

In case you want to achieve properties. There is the @property decorator:

@property
def size(self):
    return self._size

In your constructor you just define self._size and work internally with it.

Upvotes: 0

Daniel
Daniel

Reputation: 42758

With the line self.size = 0 you hide the methode size, so size is an int and not a method anymore.

Upvotes: 3

Related Questions