Shreyas Vedpathak
Shreyas Vedpathak

Reputation: 458

How to pass a variable declared inside init as default parameter to a class method in python

I'm trying to perform a recursive search operation on a Binary Search Tree by declaring a BST class. I have initialised the root value to none(as shown below).

 class BST:  

        def __init__(self):
            self._root = None
        
        def search_recursive(self, troot, key):
            if troot:
                if key == troot._element:
                    return True
                elif key < troot._element:
                    return self.search_recursive(troot._left, key)
                elif key > troot._element:
                    return self.search_recursive(troot._right, key)
            else:
                return False

What I want to do is, pass this root as default argument for the recursive search function. So when it is called for the first time, the troot value will be the root and it will get updated to whatever is passed in the later function calls. Something like this

def search_recursive(self, troot = self._root, key)

I can create a driver function and pass root as a parameter (as shown below) and get things working, but is their a way we can do as I have stated above?

  def search_driver(self, key):
      self.search_recursive(self._root, key)

Upvotes: 1

Views: 61

Answers (1)

timgeb
timgeb

Reputation: 78780

Writing a non-recursive function that makes the initial call to the recursive function is the standard approach.

In this specific case, however, you can omit the troot argument entirely, because you already have access to it via self.

class BST:    
        def __init__(self):
            self._root = None
        
        def search_recursive(self, key):
            if self._root:
                if key == self._root._element:
                    return True
                elif (key < self._root._element) and (self._root._left is not None):
                    return self._root._left.search_recursive(key)
                elif (key > self._root._element) and (self._root._right is not None):
                    return self._root._right.search_recursive(key)
            else:
                return False

You can write this code a bit more elegantly but I wanted to mimic your structure as closely as possible.

Upvotes: 1

Related Questions