0

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?

4
  • I'd suggest self._size for the data; that way you're not stomping on the method. Commented Oct 27, 2015 at 23:21
  • Is self.size a method or data? Commented Oct 27, 2015 at 23:21
  • @PeterWood, ...well, that's the problem; in the code here, it's both at different times. Commented Oct 27, 2015 at 23:21
  • But it's your code. Change it. Commented Oct 28, 2015 at 9:10

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I've typically seen the term "shadow" as opposed to "hide".
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.