如何从Python中的另一个函数调用函数内的函数?

Roh*_*ant 2 python scope function python-3.x

我在python的另一个函数中定义了一个函数,现在我想调用内部函数.这是可能的,在python?我怎么打电话func2func3

def func1():
    def func2():
        print("Hello!")

def func3():
    # Enter code to call func2 here
Run Code Online (Sandbox Code Playgroud)

mha*_*wke 11

你不能,至少不是直接的.

我不确定你为什么要那样做.如果您希望能够func2()从外部呼叫func1(),只需func2()在适当的外部范围内定义即可.

您可以这样做的一种方法是传递一个参数来func1()指示它应该调用func2():

def func1(call_func2=False):
    def func2():
        print("Hello!")
    if call_func2:
        return func2()

def func3():
    func1(True)
Run Code Online (Sandbox Code Playgroud)

但由于这需要修改现有代码,因此您可以移动func2()到相同的范围func1().


我不建议你这样做,但是,通过一些间接,你可以进入func1()函数对象并访问它的代码对象.然后使用该代码对象访问内部函数的代码对象func2().最后称之为exec():

>>> exec(func1.__code__.co_consts[1])
Hello!
Run Code Online (Sandbox Code Playgroud)

概括来说,如果您有任意顺序的多个嵌套函数,并且您希望按名称调用特定的函数:

from types import CodeType
for obj in func1.__code__.co_consts:
    if isinstance(obj, CodeType) and obj.co_name == 'func2':
        exec(obj)
Run Code Online (Sandbox Code Playgroud)