python 函数嵌套函数_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 nested functions–to serve as small helper function to a more complex outer function.

如您所见,嵌套的getFullName函数可以访问外部greeting函数的参数firstlast 。 这是嵌套函数的常见用例-充当较小的辅助函数,成为更复杂的外部函数。

使用嵌套函数的原因 (Reasons to use nested functions)

While there are many valid reasons to use nested functions, among the most common are encapsulation and closures / factory functions.

尽管有许多使用嵌套函数的正当理由,但最常见的是封装和闭包/工厂函数。

数据封装 (Data encapsulation)

There are times when you want to prevent a function or the data it has access to from being accessed from other parts of your code, so you can encapsulate it within another function.

有时您想防止某个功能或其有权访问的数据从代码的其他部分访问,因此您可以封装在另一个功能中。

When you nest a function like this, it's hidden from the global scope. Because of this behavior, data encapsulation is sometimes referred to as data hiding or data privacy. For example:

当您嵌套这样的函数时,它对全局作用域是隐藏的。 由于这种行为,数据封装有时被称为数据隐藏数据隐私 。 例如:

def outer():
  print("I'm the outer function.")
  def inner():
    print("And I'm the inner function.")
  inner()

inner()

Output:

输出:

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

In the code above, the inner function is only available from within the function outer. If you try to call inner from outside the function, you'll get the error above.

在上面的代码中, inner功能仅可从outer功能中使用。 如果尝试从函数外部调用inner ,则会收到上面的错误。

Instead, you must call the outer function like so:

相反,您必须像这样调用outer函数:

def outer():
  print("I'm the outer function.")
  def inner():
    print("And I'm the inner function.")
  inner()

outer()

Output:

输出:

I'm the outer function.
And I'm the inner function.

关闭 (Closures)

But what would happen if the outer function returns the inner function itself, rather than calling it like in the example above? In that case you would have what's known as a closure.

但是,如果外部函数返回内部函数本身,而不是像上面的示例那样调用它,将会发生什么? 在这种情况下,您将拥有所谓的闭包。

The following are the conditions that are required to be met in order to create a closure in Python:

以下是在Python中创建闭包所需满足的条件:

These are the conditions you need to create a closure in Python:

这些是在Python中创建闭包所需的条件:

1. There must be a nested function

1.必须有一个嵌套函数

1. There must be a nested function

1.必须有一个嵌套函数

2. The inner function has to refer to a value that is defined in the enclosing scope

2.内部函数必须引用在封闭范围内定义的值

2. The inner function has to refer to a value that is defined in the enclosing scope

2.内部函数必须引用在封闭范围内定义的值

3. The enclosing function has to return the nested function

3.封闭函数必须返回嵌套函数

3. The enclosing function has to return the nested function

3.封闭函数必须返回嵌套函数

- Source: https://stackabuse.com/python-nested-functions/

-来源: https//stackabuse.com/python-nested-functions/

Here's a simple example of a closure:

这是一个简单的闭包示例:

def num1(x):
  def num2(y):
    return x + y
  return num2

print(num1(10)(5))

Output:

输出:

15

Closures make it possible to pass data to inner functions without first passing them to outer functions with parameters like the greeting example at the beginning of the article. They also make it possible to invoke the inner function from outside of the encapsulating outer function. All this with the benefit of data encapsulation / hiding mentioned before.

闭包使得可以将数据传递给内部函数,而无需先将其传递给具有本文开头greeting示例之类的参数的外部函数。 它们还可以从封装外部函数的外部调用内部函数。 所有这些都具有前面提到的数据封装/隐藏的好处。

Now that you understand how and why to nest functions in Python, go out and nest 'em with the best of 'em.

既然您已经了解了如何以及为什么在Python中嵌套函数,请充分利用'em来嵌套它们。

翻译自: https://www.freecodecamp.org/news/nested-functions-in-python/

python 函数嵌套函数

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值