[英]passing self data into a recursive function
我正在嘗試設置一個函數來做這樣的事情
def __binaryTreeInsert(self, toInsert, currentNode=getRoot(), parentNode=None):
當前節點從根開始,然后在方法中將其更改為另一個節點,然后再次遞歸調用它。
但是,我無法使“ currentNode = getRoot()”正常工作。 如果我嘗試調用funcion getRoot()(如上所述),則表示未提供所有必需的變量,但是如果我嘗試調用self.getRoot(),則抱怨self是未定義的變量。 有沒有一種方法可以在我不必調用此方法時指定根的情況下做到這一點?
編輯:此方法的基本情況已經
if currentNode == None:
所以用那個來設置根是行不通的
雖然arg=None
是用於非提供的參數的慣用的Python標記值,它不必須是None
。 例如,在Lua中,慣用的不提供的參數是一個空表。 實際上,我們可以將其應用於這種情況:
class Foo:
sentinel = {}
def bar(self, arg=sentinel):
if arg is self.sentinel:
print "You didn't supply an argument!"
else:
print "The argument was", arg
f = Foo()
f.bar(123)
f.bar()
f.bar(None)
f.bar({})
輸出:
The argument was 123 You didn't supply an argument! The argument was None The argument was {}
這適用於除顯式傳遞Foo.sentinel
之外的任何情況,因為Foo.sentinel
保證具有唯一地址-意味着, x is Foo.sentinel
僅當x 是 Foo.sentinel
時才是 Foo.sentinel
:)因此,由於閉包,我們在Foo.sentinel
周圍創建的對象中,只有一個對象會造成模棱兩可的情況,並且永遠不會偶然使用它。
你可以做
def __binaryTreeInsert(self, toInsert, currentNode=None, parentNode=None):
if currentNode is None:
currentNode = self.getRoot()
...
定義函數或方法后,將立即評估def
行,包括所有關鍵字參數。 因此,函數調用和可變對象之類的內容通常不適用於默認參數。
解決方案是使用哨兵值。 None
是最常見的,但是對於None
將是有效值的情況,您可以使用另一個標記,例如:
not_provided = object()
def _binaryTreeInsert(self, toInsert, currentNode=not_provided, parentNode=None):
if currentNode is not_provided:
currentNode = self.getRoot()
def __binaryTreeInsert(self, toInsert, currentNode=0, parentNode=None):
if not currentNode:
currentNode = self.getRoot()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.