简体   繁体   中英

Python functions calling functions inside functions

In Python, say I have the following code:

def func0():
    print("This is func0")
    
def func1():

    print("func1 calls func0")
    func0()


def func2():
    def func21():
        print("This is func21")

    print("func2 can call func0")
    func0()

    print("It can also call funct21")
    func21()


func_0()
func_1()
func_2()

Is there a way to get func1() to call func21()? Or do I simply need to pull func21() out of func2()?

I couldn't find anything online, thought I'd try here.

TIA!

If you can't move the function out for some specific reason, you can try adding func21 directly into the local scope (in the example you sent, the function is defined in the enclosing scope).

def func0():
  print("This is func0")
    
def func1():
  print("func1 calls func0")
  func0()
  func21()


def func2():
  locals()["func21"] = lambda:print("This is func21")

  print("func2 can call func0") 
  func0()

  print("It can also call funct21")
  func21()


func0()
func1()
func2()

or

def func0():
  print("This is func0")
    
def func1():
  print("func1 calls func0")
  func0()
  func21()


def func2():
  def func21():
    print("This is func21")
    
  locals()["func21"] = func21

  print("func2 can call func0") 
  func0()

  print("It can also call funct21")
  func21()


func0()
func1()
func2()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM