关于递归:python-函数可以不显式使用名称而调用自己吗?

Python - can function call itself without explicitly using name?

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

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

1
2
3
4
5
6
7
8
9
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


我不知道你为什么要这样做,但尽管如此,你还是可以用一个装饰师来实现这一点。

1
2
3
4
def recursive_function(func):
    def decorator(*args, **kwargs):
        return func(*args, my_func=func, **kwargs):
    return decorator

然后你的功能是:

1
2
3
@recursive_function
def my_recursive_function(my_func=None):
    ...

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

1
2
3
4
5
class Foo(object):

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