2017-10-19 47 views
0

作爲靜態方法實現遞歸函數的正確方法是什麼?作爲靜態方法的遞歸函數

這是我如何使它工作atm。我想知道是否有實現這一目標,留下一個更清潔的內存佔用的「更好」的方式,看起來更Python等

class MyClass(object): 
    @staticmethod 
    def recursFun(input): 
     # termination condition 
     sth = MyClass().recursFun(subinput) 
     # do sth 
     return sth 
+0

老實說,如果你正在尋找Pythonic,我只是不會使用'staticmethod' –

+0

你會怎麼做它在oop python? – r2d2oid

+0

我簡直不會讓它成爲類的一部分,並且使其成爲模塊級功能。很難說沒有更多的細節。 –

回答

4

你不需要類的實例來進行正確的名稱查找;班級本身也會這樣做。因爲當你執行名稱查找,recursive_function不會在範圍

class MyClass(object): 
    @staticmethod 
    def recursive_function(input): 
     # ... 
     sth = MyClass.recursive_function(subinput) 
     # ... 
     return sth 

合格的名稱是必要的;只有MyClass.recursive_function會。

0

使它成爲一個classmethod代替:

class MyClass(object): 

    @classmethod 
    def recursFun(celf, input): 
     # termination condition 
     sth = celf.recursFun(subinput) 
     # do sth 
     return sth 
    #end recursFun 

#end MyClass 

這也使得它更容易繼承類,如果您需要。