如何在Python中从另一个函数调用一个函数中的一个函数? [英] How to call a function within a function from another function in Python?

查看:54
本文介绍了如何在Python中从另一个函数调用一个函数中的一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在python中的另一个函数中定义了一个函数,现在我想调用内部函数.在python中有可能吗?如何从 func3 调用 func2 ?

I have defined a function within another function in python and now I would like to call the inner function. Is this possible, in python? How do I call func2 from func3?

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

def func3():
    # Enter code to call func2 here

推荐答案

您不能,至少不能直接这样做.

You can't, at least not directly.

我不确定您为什么要这么做.如果您希望能够从 func1()外部调用 func2(),只需在适当的外部范围内定义 func2().

I'm not sure why you would want to do that. If you want to be able to call func2() from outside func1(), simply define func2() at an appropriate outer scope.

您可以执行的一种方法是将参数传递给 func1(),指示该参数应调用 func2():

One way that you could do it is to pass a parameter to func1() indicating that it should invoke func2():

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

def func3():
    func1(True)

但是由于需要修改现有代码,因此您最好将 func2()移到与 func1()相同的作用域.

but since that requires modification to the existing code, you might as well move func2() to the same scope as func1().

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

I don't recommend that you do this, however, with some indirection you can reach into the func1() function object and access it's code object. Then using that code object access the code object for the inner function func2(). Finally call it with exec():

>>> exec(func1.__code__.co_consts[1])
Hello!

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

To generalise, if you had multiple nested functions in an arbitrary order and you wanted to call a specific one by name:

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

这篇关于如何在Python中从另一个函数调用一个函数中的一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆