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):
    if n < 1:
        return 1
    return n * fact(n-1)

有没有人有什么想法?

编辑:

我的问题不同于Determine function name from within that function (without using traceback) .我需要在上面的代码中使用 fact == this 来返回 True

编辑 2:

@ksbg 的回答很好,但请考虑以下代码:

from inspect import stack, currentframe

def a():
    def a():
        f_name = stack()[0][3]  # Look up the function name as a string
        this = currentframe().f_back.f_globals[f_name]
        print(a == this)
    a()

a() # False

在这种情况下,它不会按预期工作。

最佳答案

这可以通过检查堆栈跟踪来完成。首先我们以字符串形式查找函数名称,然后我们返回一个框架(或级别),并从模块的全局变量中获取该函数:

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 中不可能在不检查堆栈跟踪的情况下执行此操作。

关于python - 如何在不直接命名的情况下从其中访问函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51873133/

相关文章:

python - 将 settings.py 配置文件加载到字典中

python - 如何在全局保存 header api

python - 有谁知道如何在 pygame 上的某个坐标处制作图像?

python - 如何优化几何运算的性能

python - 如何检查注释是否是 Python 中的 ClassVar?

python - 修改数组不会影响其在外循环中的长度

Python:包含字符串子列表的列表

python - 如何创建非阻塞函数?

c++ - 来自 C++ 的 Python 回溯

python - 在遍历字典列表时避免 KeyError