Class object mistaken as an int

Viewed 46

I am making a tree class to practice, and I have arrived at this.

class Node():
def __init__(self,val):
    self.val = val
    self.right = None
    self.left = None
    self.count = 1
def add(self,node):
    if self.val > node.val:
        if self.left == None:
            self.left = node
        else:
            self.left.add(node)
    elif self.val < node.val:
        if self.right == None:
            self.right = node
        else:
            self.right.add(node)
    else:
        self.count +=1
def count(self):
    if self.right and self.left:
        self.right.count()
        self.left.count()
    elif self.right:
        print(self.value)
        self.right.count()
    elif self.left:
        print(self.value)
        self.left.count()
    else:
        pass

But, when calling it, I have a problem.

a = Node('a')
>>> a.add(Node('a'))
>>> a.add(Node('b'))
>>> a.count()
Traceback (most recent call last):
  File "<pyshell#73>", line 1, in <module>
    a.count()
TypeError: 'int' object is not callable
>>> 

>>> type(a.right)
<class '__main__.Node'>

How can I fix this? Through debugging, it seems the problem is at self.right.count() function. Also, I am on Python 3.9.4.

2 Answers

You have an int field and method count. Rename one of them and problem will be solved. Also you have

print(self.value)

line, but your field name is val.

The integer referred to in the error is a.count. The problem is that count is used in two ways by the class: (1) as a method name, and (2) as an instance attribute name.

When an instance of Node is created, the __init__ method creates an instance attribute count in the following:

    self.count = 1

This masks the method of the same name. So when you do a.count(), it's using 1 for a.count.

To fix it, just use different names for method vs. the instance attribute.

Related