将自身数据传递给递归函数
我试图设置一个函数来执行类似的操作,
def __binaryTreeInsert(self, toInsert, currentNode=getRoot(), parentNode=None):
其中当前节点作为根启动,然后我们将其更改为方法中的不同节点并再次递归调用它。
但是,我无法让“currentNode=getRoot()”工作。如果我尝试调用函数 getRoot() (如上所述),它会说我没有给它所有必需的变量,但如果我尝试调用 self.getRoot() ,它会抱怨 self 是一个未定义的变量。有没有一种方法可以在调用此方法时无需指定根来执行此操作?
编辑:此方法的基本情况已经存在,
if currentNode == None:
因此使用它来设置根是行不通的
I'm trying to set a function to do something like this
def __binaryTreeInsert(self, toInsert, currentNode=getRoot(), parentNode=None):
where current node starts as root, and then we change it to a different node in the method and recursivly call it again.
However, i cannot get the 'currentNode=getRoot()' to work. If i try calling the funcion getRoot() (as above) it says im not giving it all the required variables, but if i try to call self.getRoot() it complains that self is an undefined variable. Is there a way i can do this without having to specify the root while calling this method?
EDIT: The base case of this method is already
if currentNode == None:
so using that to set the root wouldn't work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然
arg=None
是非提供参数的惯用 Python 哨兵值,但它不一定为None
。例如,在 Lua 中,惯用的非提供参数是一个空表。我们实际上可以将其应用于这种情况:输出:
这适用于除显式传递 Foo.sentinel 之外的任何情况,因为保证 Foo.sentinel 具有唯一的地址 -意思是,
x is Foo.sentinel
仅当 x isFoo.sentinel
时才为 true :) 因此,由于我们围绕 Foo.sentinel 创建的闭包,只有一个对象可以创建不明确的情况,并且永远不会意外使用它。While
arg=None
is the idiomatic Python sentinel value for an non-supplied argument, it doesn't have to beNone
. In Lua, for instance, the idiomatic non-supplied argument is an empty table. We can actually apply that to this case:Output:
This works for any case except explicitly passing
Foo.sentinel
, becauseFoo.sentinel
is guaranteed to have a unique address -- meaning,x is Foo.sentinel
is only true when x isFoo.sentinel
:) Thus, due to the closure we've created aroundFoo.sentinel
, there is only one object that can create an ambiguous situation, and it will never be used by accident.你可以做
You can do
定义函数或方法时,会立即计算
def
行,包括任何关键字参数。因此,函数调用和可变对象之类的东西通常不适合默认参数。解决方案是使用哨兵值。
None
是最常见的,但对于None
是有效值的情况,您可以使用另一个哨兵,例如:When a function or method is defined, the
def
line is evaluated immediately, including any keyword arguments. For this reason, things like function calls and mutable objects are usually not appropriate for default arguments.The solution is instead to use a sentinel value.
None
is most common, but for the cases thatNone
would be a valid value, you can use another sentinel, for example: