Python 如何在不直接命名的情况下从函数中访问函数
我想知道如何在不直接命名的情况下从函数中访问函数Python 如何在不直接命名的情况下从函数中访问函数,python,Python,我想知道如何在不直接命名的情况下从函数中访问函数 def fact(n): this = # some code, where we don't use the name "fact" print(fact == this) # True if n < 1: return 1 return n * this(n-1) 在这种情况下,它将无法按预期工作。这可以通过检查堆栈跟踪来完成。首先,我们以字符串形式查找函数名,然后返回一帧(或级别),并
def fact(n):
this = # some code, where we don't use the name "fact"
print(fact == this) # True
if n < 1:
return 1
return n * this(n-1)
在这种情况下,它将无法按预期工作。这可以通过检查堆栈跟踪来完成。首先,我们以字符串形式查找函数名,然后返回一帧(或级别),并从模块的全局变量中获取函数:
from inspect import stack, currentframe
f_name = stack()[0][3] # Look up the function name as a string
this = currentframe().f_back.f_globals[f_name] # Go back one level (to enter module level) and load the function from the globals
但是,我不认为这是一个好的实践,如果可能的话,我会避免这样做。正如在对您的问题的评论中已经指出的,在Python中不检查堆栈跟踪是不可能的。这可以通过检查堆栈跟踪来完成。首先,我们以字符串形式查找函数名,然后返回一帧(或级别),并从模块的全局变量中获取函数:
from inspect import stack, currentframe
f_name = stack()[0][3] # Look up the function name as a string
this = currentframe().f_back.f_globals[f_name] # Go back one level (to enter module level) and load the function from the globals
但是,我不认为这是一个好的实践,如果可能的话,我会避免这样做。正如在对您的问题的评论中已经指出的那样,在Python中不检查堆栈跟踪是不可能的。为什么要这样做?为什么要这样做?这是一个很好的方法,但请看我文章中的
EDIT2
。这是一个很好的方法,但请看我文章中的EDIT2
。
from inspect import stack, currentframe
f_name = stack()[0][3] # Look up the function name as a string
this = currentframe().f_back.f_globals[f_name] # Go back one level (to enter module level) and load the function from the globals