python 函数嵌套函数_Python中的嵌套函数

  • Post author:
  • Post category:python


python 函数嵌套函数

A nested function is simply a function within another function, and is sometimes called an “inner function”. There are many reasons why you would want to use nested functions, and we’ll go over the most common in this article.

嵌套函数只是另一个函数中的一个函数,有时也称为“内部函数”。 为什么要使用嵌套函数有很多原因,我们将在本文中介绍最常见的函数。

如何定义一个嵌套函数

(

How to define a nested function

)

To define a nested function, just initialize another function within a function by using the

def

keyword:

要定义一个嵌套函数,只需使用

def

关键字在一个函数中初始化另一个函数:

def greeting(first, last):
  # nested helper function
  def getFullName():
    return first + " " + last

  print("Hi, " + getFullName() + "!")

greeting('Quincy', 'Larson')


Output:


输出:

Hi, Quincy Larson!

As you can see, the nested

getFullName

function has access to the outer

greeting

function’s parameters,

first

and

last

. This is a common use case for ne