Python中嵌套函数是如何工作的?

Python中嵌套函数是如何工作的?

在本文中,我们将通过示例解释Python中的嵌套/内部函数及其工作原理。

嵌套(或内部)函数是在其他函数内部定义的函数,允许我们直接访问封装函数中定义的变量和名称。嵌套函数可用于创建闭包和装饰器,以及其他一些用途。

定义内部/嵌套函数

只需在函数内部使用 def 关键字初始化另一个函数来定义一个 嵌套 函数。

以下程序演示了Python中的内部函数 –

示例

# creating an outer function
def outerFunc(sample_text):
   sample_text = sample_text
# creating an inner function
   def innerFunc():
# Printing the variable of the parent class(outer class)
      print(sample_text)
# calling inner function
   innerFunc()
# Calling the outer Function by passing some random name
outerFunc('Hello tutorialspoint python')

输出

在执行时,上述程序将会生成以下输出:

Hello tutorialspoint python

在这里,innerFunc()outerFunc()内部声明,使其成为内部函数。我们必须先调用outerFunc(),然后才能调用innerFunc()。而outerFunc()会调用定义在其中的innerFunc()

外部函数的调用对于内部函数的执行是至关重要的。

没有调用外部函数

示例

# creating an outer function
def outerFunc(sample_text):
    sample_text = sample_text
    # creating an inner function
    def innerFunc():
       print(sample_text)
 # calling inner function
    innerFunc()

输出

执行上述程序后,将生成以下输出-
运行以上代码将不返回任何结果。

嵌套函数中的变量范围

变量的范围是我们可以找到变量并在需要时访问它的位置。

如何在函数内部访问全局变量是非常清楚的,那么如何访问外部函数的变量呢?

以下程序演示了嵌套函数的作用域 –

示例

# creating an outer function
def outerFunc():
   sample_str = 'Hello tutorialspoint python'

   # creating an inner function
   def innerFunc():
      print(sample_str)

   # calling an inner function inside the outer function
   innerFunc()
# calling outer function
outerFunc()

输出

在执行上述程序时,将生成以下输出 –

Hello tutorialspoint python

从上面的例子可以清楚地看出,这等同于从函数中访问一个全局变量。

假设你希望修改外部函数的变量。

示例

以下程序改变了嵌套函数(内部函数)中的变量的值-

# creating an outer function
def outerFunc():
   sample_str = 'Hello tutorialspoint python'
# creating an inner function
   def innerFunc():
   # modifying the sample string
      sample_str = 'Welcome'
      print(sample_str)
# calling an inner function inside the outer function
   innerFunc()
   print(sample_str)
# calling outer function
outerFunc()

输出

在执行后,上述程序将生成以下输出−

Welcome
Hello tutorialspoint python

在这里,外部函数变量的值保持不变。然而,外部函数变量的值可以被修改。有多种方法可以改变外部函数变量的值。

使用内部函数的可迭代对象

下面的程序演示了如何在内部函数中使用可迭代对象进行修改。

# Creating outer function
def outerFunc():
   # Creating an iterable
      sample_str = ['Hello tutorialspoint python']
      # Creating inner Function/Nested Function
      def innerFunc():
      # using an iterable to modify the value
         sample_str[0] = 'Welcome'
         print(sample_str)
      # Calling the inner function
      innerFunc()
   # Printing variable of the outer function
      print(sample_str)
# Calling the outer function
outerFunc()

输出

执行上述程序后将会产生以下输出-

['Welcome']
['Welcome']

为什么应该使用嵌套函数?

封装和闭包/工厂函数是使用嵌套函数的两个最常见的原因。

数据封装

在某些情况下,您希望封装一个函数或其访问的数据,以防止它被其他代码部分访问。

当您像这样嵌套一个函数时,它对全局范围来说是隐藏的。由于这个特性,数据封装也被称为数据隐藏或数据私密性。

# creating an outer function
def outerFunc():
   print("This is outer function")
   # creating an inner function
   def innerFunc():
      print("This is inner function")

   # calling an inner function inside the outer function
   innerFunc()
# calling inner function outside the outer function
innerFunc()

输出

执行以上程序后,将生成以下输出结果:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    innerFunc()
NameError: name 'innerFunc' is not defined

上面的代码中的内部函数只能从外部函数内部访问。如果你尝试从函数外部调用内部函数,你将看到上面显示的错误。

相反,你必须按照以下方式调用外部函数。

# creating an outer function
def outerFunc():
   print("This is outer function")
   # creating an inner function
   def innerFunc():
      print("This is inner function")

   # calling an inner function inside the outer function
   innerFunc()
# calling outer function
outerFunc()

输出

执行上述程序后,将会生成以下输出−

This is outer function
This is inner function

闭包

但是,如果外部函数返回的是内部函数本身,而不是像之前的例子中那样调用它呢?在这种情况下,你会得到一种被称为闭包的东西。

在Python中创建闭包的必要条件如下。

  • 需要一个嵌套函数。

  • 内部函数必须引用在封闭范围中定义的值。

  • 嵌套函数必须由封闭函数返回。

例子

def number_1(a):
   def number_2(b):
      return a*b
   return number_2
print(number_1(3)(2))

输出

在执行后,上述程序将生成以下输出 –

6

闭包 允许您将数据传递给内部函数,而无需首先通过参数传递给外部函数。它们还允许从封装的外部函数之外调用内部函数。所有这些都具有先前提到的数据封装/隐藏的好处。

结论

本文向我们介绍了内部函数、嵌套函数的目的、它们的工作原理以及Python中嵌套函数的作用域。

从这里开始学习Python:Python教程

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程