简体   繁体   English

如何调用一个函数,它在python中的另一个函数中定义?

[英]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... 我只想调用“内部”函数...最终输出应该只打印var2而不是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. 您将无法从out外部函数调用inner ,因为inner仅在out inner定义,除非您从out外部函数创建对inner的引用。 In addition, inner is not outputting anything since it does not have a print statement. 另外,由于inner没有打印语句,因此inner不输出任何内容。

To combat this, you have two options: 为了解决这个问题,您有两种选择:

  • Place inner in a broader scope (ie outside out ) and add to it a print(var1) statement. inner放在更广泛的范围内(即outside out之外),并在其中添加一个print(var1)语句。
  • 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 ; 如果需要inner的功能在里面out然后就返回inner封闭out ,用print语句也在里面inner ; or just call it from inside out . 或者只是从内而out调用它。 This has a side-effect of also executing whatever statements are inside out up to returning the closure. 这也执行任何语句是内部的副作用out了久违关闭。

The method your trying is called as nested functions: 您尝试的方法称为嵌套函数:

You can chek this answer for information about nested function in Python . 您可以查看该答案以获取有关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: 范例2:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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