<分区>
我想知道如何在不直接命名的情况下从其中访问函数。
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
在这种情况下,它不会按预期工作。