【问题标题】:calling a function inside another function(nested)在另一个函数中调用一个函数(嵌套)
【发布时间】:2018-04-09 17:36:27
【问题描述】:

我在 Python 中有一个函数

def outer_function():
    def inner_funtion():
        print ('inner message')
    print('outer message')
    sys.exit()

如何调用内部函数?我对检查库很陌生,如果这符合关闭条件,我会关闭。

【问题讨论】:

  • 您调用它的方式与调用任何其他函数的方式相同...inner_funtion().
  • Nested Function in Python的可能重复

标签: python python-3.x closures nested-function


【解决方案1】:

您可以将其称为任何其他函数 inner_funtion(),但显然它只能在 outer_function 范围内访问。

【讨论】:

    【解决方案2】:

    您可以在定义inner_function() 的范围内的任何位置使用inner_function(),即定义inner_function() 之后的outer_function() 中的任何位置。

    【讨论】:

      【解决方案3】:

      我发现自己经常使用这种技术。 正如其中一位评论者所写,您只需称呼它:

      def outer_function():
          def inner_funtion():
              print ('inner message')
          print('outer message')
          inner_function()
          sys.exit()
      
      >>> outer_function()
      outer message
      inner message
      

      这仅在outer_function() 范围内有效,如果您尝试在outer_function() 之外的任何地方调用inner_function(),则会返回错误。

      使用嵌套函数是清理其他难以处理的*函数的好方法。

      关于你的第二个问题,the top answer here 做得比我做得更好。

      【讨论】: