2017-10-19 30 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 

这也使得它更容易继承类,如果您需要。