Call a function defined in another function

前端 未结 4 1959
梦谈多话
梦谈多话 2020-11-28 14:44

Can I call a function nested inside another function from the global scope in python3.2?

def func1():
    def func2():
        print(\"Hello\")
        retur         


        
相关标签:
4条回答
  • 2020-11-28 15:05

    No, unless you return the function:

    def func1():
        def func2():
            print("Hello")
        return func2
    
    innerfunc = func1()
    innerfunc()
    

    or even

    func1()()
    
    0 讨论(0)
  • 2020-11-28 15:19

    This is based on eyquem's solution.

    def func1():
        global func2  # put it in global scope
        def func2():
            print("Hello")
    

    Now you can invoke func2 directly.

    But func1() would have to be called before you can call func2() otherwise it will not have been defined yet.

    0 讨论(0)
  • 2020-11-28 15:22
    def func1():
        def func2():
            global fudu
            fudu = func2
            print("Hello")
        func2()
    
    
    func1()
    
    fudu()
    
    print 'fudu' in dir()
    print 'func2' in dir()
    

    result

    Hello
    Hello
    True
    False
    

    Also:

    def func1():
        global func2
        def func2():
            print("Hello")
        func2()
    
    
    func1()
    
    print 'func2' in dir()
    func2()
    

    result

    Hello
    True
    Hello
    

    What's the interest?

    0 讨论(0)
  • 2020-11-28 15:27

    You want to use @larsmans' solution, but theoretically you can cut yourself into the code object of the locally accessible func1 and slice out the code object of func2 and execute that:

    #!/usr/bin/env python
    
    def func1():
        def func2():
            print("Hello")
    
    # => co_consts is a tuple containing the literals used by the bytecode
    print(func1.__code__.co_consts)
    # => (None, <code object func2 at 0x100430c60, file "/tmp/8457669.py", line 4>)
    
    exec(func1.__code__.co_consts[1])
    # => prints 'Hello'
    

    But again, this is nothing for production code.

    Note: For a Python 2 version replace __code__ with func_code (and import the print_function from the __future__).

    Some further reading:

    • http://web.archive.org/web/20081122090534/http://pyref.infogami.com/type-code
    • http://docs.python.org/reference/simple_stmts.html#exec
    • http://lucumr.pocoo.org/2011/2/1/exec-in-python/
    0 讨论(0)
提交回复
热议问题