简体   繁体   中英

How to call a function, it define in another function in python?

def out():
   var1 = "abc"
   print(var1)

   def inner():
      var2 = "def"

I want to call only "Inner" function... the final output should print only var2 not var1...

Thank you in advance

If you don't want to run some part of the function 'out' you could use parameters.

def out(choice=True):
  if choice :
    var1 = "abc"
    print(var1)
 else :
    def inner():
       var2 = "def"
       print(var2)
    inner()

You will not be able to call inner from outside the out function, since inner is only defined inside out , unless you create a reference to inner from outside the out function. In addition, inner is not outputting anything since it does not have a print statement.

To combat this, you have two options:

  • Place inner in a broader scope (ie outside out ) and add to it a print(var1) statement.
  • If it is required to have the inner function be inside out then just return inner as a closure from out , with the print statement also inside inner ; or just call it from inside out . This has a side-effect of also executing whatever statements are inside out up to returning the closure.

The method your trying is called as nested functions:

You can chek this answer for information about nested function in Python .

Some other information about closure

Another method is,

def fun1():
    x = 11
    def fun2(a=a):
        print x
    fun2()

fun1()

Output:

prints 11

Example 2:

def f1(x):
    def add(y):
        return x + y
    return add

res = f1(5)
print(res(10))  # prints 15

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