[英]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).我正在尝试通过声明 BST class 对二叉搜索树执行递归搜索操作。我已将根值初始化为无(如下所示)。
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.我想要做的是,将此根作为递归搜索 function 的默认参数传递。因此,当它第一次被调用时,根值将是根,并且它将更新为在以后的 function 调用中传递的任何值. 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?我可以创建一个驱动程序 function 并将 root 作为参数传递(如下所示)并让一切正常工作,但他们是我们可以按照我上面所说的那样做的方式吗?
def search_driver(self, key):
self.search_recursive(self._root, key)
Writing a non-recursive function that makes the initial call to the recursive function is the standard approach.编写对递归 function 进行初始调用的非递归 function 是标准方法。
In this specific case, however, you can omit the troot
argument entirely, because you already have access to it via self
.但是,在这种特定情况下,您可以完全省略
troot
参数,因为您已经可以通过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.您可以更优雅地编写此代码,但我想尽可能地模仿您的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.