<分区>
我在 python 中的另一个函数中定义了一个函数,现在我想调用内部函数。这可能吗,在 python 中?
如何从 func3
调用 func2
?
def func1():
def func2():
print("Hello!")
def func3():
# Enter code to call func2 here
<分区>
我在 python 中的另一个函数中定义了一个函数,现在我想调用内部函数。这可能吗,在 python 中?
如何从 func3
调用 func2
?
def func1():
def func2():
print("Hello!")
def func3():
# Enter code to call func2 here
最佳答案
你不能,至少不能直接。
我不确定您为什么要这样做。如果您希望能够从 func1()
外部调用 func2()
,只需在适当的外部范围内定义 func2()
。
您可以这样做的一种方法是将参数传递给 func1()
,指示它应该调用 func2()
:
def func1(call_func2=False):
def func2():
print("Hello!")
if call_func2:
return func2()
def func3():
func1(True)
但由于这需要修改现有代码,您不妨将 func2()
移动到与 func1()
相同的范围。
我不建议您这样做,但是,通过一些间接方式,您可以访问 func1()
函数对象并访问它的代码对象。然后使用该代码对象访问内部函数 func2()
的代码对象。最后用 exec()
调用它:
>>> exec(func1.__code__.co_consts[1])
Hello!
概括地说,如果您有多个任意顺序的嵌套函数,并且您想按名称调用特定函数:
from types import CodeType
for obj in func1.__code__.co_consts:
if isinstance(obj, CodeType) and obj.co_name == 'func2':
exec(obj)
关于python - 如何从 Python 中的另一个函数调用函数内的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48049474/