LEO BABY JACOB
LEO BABY JACOB

Reputation: 33

Error in tree implementation with Python

I am trying to implement a tree in Python but I get an error inside a method declaration.

I believe that it is due to the self instance I used:

class Node:

   def __init__(self, data=None, l=None, r=None):
       self.data = data
       self.l = l
       self.r = r

class Tree:
   def __init__(self):
       self.root = Node()

I am trying to send a node for inserting but if nothing is sent I want to reference it with the root

  def insert(self,data,root1=self.root):
      '''function definition'''

t = Tree()
t.insert(1)

Upvotes: 3

Views: 89

Answers (2)

Jared Goguen
Jared Goguen

Reputation: 9010

Instance methods are created when a class is defined and the default argument is added to the unbound method as member data. This all occurs before the class could ever be instantiated, thus there is no such self to reference. This is tangentially related to the common mutable default argument issue. Consider the following piece of code:

class Test:
    def method(self, arg='default argument'):
        pass

print(Test.method) # <unbound method Test.method>
print(Test.method.__func__.func_defaults) # ('default argument',)

Here, how would Test.method have any idea what self is when no instance of the class has ever been created? Instead you probably want to use the following pattern:

def insert(self, data, root=None):
    if root is None:
        root = self.root
    # ...

Upvotes: 3

PRMoureu
PRMoureu

Reputation: 13327

You cannot use self inside a method signature, the class doesn't know how to handle it, because self is only define inside the method (thanks to the first parameter).

You could use a pattern like the following :

def insert(self, data, root1=None):
    if root1 is None:
        root1 = self.root
    else:
        [...]

Upvotes: 3

Related Questions