作为静态方法的递归函数

2024-06-11 20:14:44 发布

您现在位置:Python中文网/ 问答频道 /正文

将递归函数实现为静态方法的正确方法是什么?在

这是我如何让它在atm机上工作的。我想知道是否有一种“更好”的方法来实现这一点,留下更干净的内存空间,看起来更像Python,等等

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

Tags: 方法inputobjectdefmyclassconditionclass机上
2条回答

将其改为classmethod

class MyClass(object):

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

#end MyClass

如果需要的话,这也使得类的子类化更容易。在

不需要类的实例来执行正确的名称查找;类本身就可以。在

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

限定名是必需的,因为当您执行名称查找时,recursive_function不在作用域内;只有MyClass.recursive_function才在作用域内。在

相关问题 更多 >