gpt4 book ai didi

Python - 函数可以在不显式使用名称的情况下调用自身吗?

转载 作者:太空狗 更新时间:2023-10-30 00:10:20 26 4
gpt4 key购买 nike

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

最佳答案

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

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

关于Python - 函数可以在不显式使用名称的情况下调用自身吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33205600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com