6 python recursion refactoring inspection
或者更广泛的问题:如何在python中创建递归函数,并且在更改其名称时,只需要在声明中进行更改?
小智 5
我找到了一个简单有效的解决方案。
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
Run Code Online (Sandbox Code Playgroud)