Python - 可以在不明确使用名称的情况下调用自身吗?

时间:2015-10-19 02:13:57

标签: python recursion refactoring inspection

或者更广泛的问题:如何在python中创建递归函数,并且在更改其名称时,只需要在声明中进行更改?

5 个答案:

答案 0 :(得分:3)

我找到了一个简单,有效的解决方案。

from functools import wraps

def recfun(f):
    @wraps(f)
    def _f(*a, **kwa): return f(_f, *a, **kwa)
    return _f

@recfun
# it's a decorator, so a separate class+method don't need to be defined
# for each function and the class does not need to be instantiated,
# as with Alex Hall's answer
def fact(self, n):
    if n > 0:
        return n * self(n-1)  # doesn't need to be self(self, n-1),
                              # as with lkraider's answer
    else:
        return 1

print(fact(10))  # works, as opposed to dursk's answer

答案 1 :(得分:0)

这是一个(未经测试的)想法:

class Foo(object):

    def __call__(self, *args):
        # do stuff
        self(*other_args)

答案 2 :(得分:0)

我不知道您为什么要这样做,但是,您可以使用decorator来实现这一目标。

def recursive_function(func):
    def decorator(*args, **kwargs):
        return func(*args, my_func=func, **kwargs):
    return decorator

然后你的功能看起来像:

@recursive_function
def my_recursive_function(my_func=None):
    ...

答案 3 :(得分:0)

您可以将函数绑定到自身,因此它接收对自身的引用作为第一个参数,就像绑定方法中的self一样:

def bind(f):
    """Decorate function `f` to pass a reference to the function
    as the first argument"""
    return f.__get__(f, type(f))

@bind
def foo(self, x):
    "This is a bound function!"
    print(self, x)

来源:https://stackoverflow.com/a/5063783/324731

答案 4 :(得分:0)

免责声明:肮脏的解决方案,但不需要装饰器

import sys

def factorial(x):
    _f = eval(sys._getframe().f_code.co_name)
    return x if x<3 else x*_f(x-1)

>>> factorial(5)
120