Python - 函数可以在不显式使用名称的情况下调用自身吗?
Python - can function call itself without explicitly using name?
或者更广泛的问题:如何在 python 中创建一个递归函数,并且在更改其名称时,只需在声明中更改它?
这是一个(未经测试的)想法:
class Foo(object):
def __call__(self, *args):
# do stuff
self(*other_args)
我不知道你为什么要这样做,但尽管如此,你可以使用 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):
...
您可以将函数绑定到自身,因此它接收对自身的引用作为第一个参数,就像绑定方法中的 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)
来源:
我找到了一个简单有效的解决方案。
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
免责声明:肮脏的解决方案,但不需要装饰器
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
或者更广泛的问题:如何在 python 中创建一个递归函数,并且在更改其名称时,只需在声明中更改它?
这是一个(未经测试的)想法:
class Foo(object):
def __call__(self, *args):
# do stuff
self(*other_args)
我不知道你为什么要这样做,但尽管如此,你可以使用 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):
...
您可以将函数绑定到自身,因此它接收对自身的引用作为第一个参数,就像绑定方法中的 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)
来源:
我找到了一个简单有效的解决方案。
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
免责声明:肮脏的解决方案,但不需要装饰器
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