gpt4 book ai didi

python - 如何在不直接命名的情况下从其中访问函数

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:35 25 4
gpt4 key购买 nike

<分区>

我想知道如何在不直接命名的情况下从其中访问函数。

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

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

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