我已经在 python 中的另一个函数中定义了一个函数,现在我想调用内部函数。在Python中这可能吗?
我怎么打电话func2
from func3
?
def func1():
def func2():
print("Hello!")
def func3():
# Enter code to call func2 here
你不能,至少不能直接。
我不确定你为什么要这样做。如果您希望能够致电func2()
从外面func1()
,简单定义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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)