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函数的参数first和last 。 这是嵌套函数的常见用例-充当较小的辅助函数,成为更复杂的外部函数。

使用嵌套函数的原因 (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

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 函数嵌套函数

python函数def里面嵌套def_python 函数嵌套函数_Python中的嵌套函数相关推荐

  1. 课后习题5.13 编写一程序,将两个字符串连接起来,结果取代第一个字符串。 (1)用字符数组,不用stract函数(即自己写一个具有stract函数功能的函数); (2)用标准库中的stract函数;

    课后习题5.13 编写一程序,将两个字符串连接起来,结果取代第一个字符串. (1)用字符数组,不用stract函数(即自己写一个具有stract函数功能的函数): (2)用标准库中的stract函数: ...

  2. python的作用域分别有几种_python中作用域与函数嵌套

    知识回顾: 拆解传参. 1.字典传参.使用** 2.列表传参.使用* 实际上我们在定义函数的时候,如果省略了星号,那么在调用函数的时候必须要省略星号,除非我们拆解后的参数个数刚好相等. 视频内容 本节 ...

  3. python嵌套列表操作方法_python中多层嵌套列表的拆分方法

    场景:有一个多层嵌套的列表如:[[23],[3,3],[22,22],1,123,[[123,a],2]] 拆分成: def splitlist(list): ''' 现有一个列表,里面元素包括 数字 ...

  4. python 一等公民_Python中一等公民——函数

    Python中"一等公民"--函数 Python的函数是"一等公民". 你可以将它们分配给变量,将它们存储在数据结构中,将它们作为参数传递给其他函数,甚至将它们 ...

  5. python pprint用法_Python中使用pprint函数进行格式化输出的教程

    pprint – 美观打印 作用:美观打印数据结构 pprint 包含一个"美观打印机",用于生成数据结构的一个美观视图.格式化工具会生成数据结构的一些表示,不仅可以由解释器正确地 ...

  6. 如何用python生成软件_python中的生成器函数是如何工作的?

    1. python中的普通函数是怎么运行的? 当一个python函数在执行时,它会在相应的python栈帧上运行,栈帧表示程序运行时函数调用栈中的某一帧.想要获得某个函数相关的栈帧,则必须在调用这个函 ...

  7. 在python中使用什么函数进行输出_Python中使用pprint函数进行格式化输出的教程

    pprint – 美观打印 作用:美观打印数据结构 pprint 包含一个"美观打印机",用于生成数据结构的一个美观视图.格式化工具会生成数据结构的一些表示,不仅可以由解释器正确地 ...

  8. python 高级使用实例_Python中的高级函数map/reduce使用实例

    怎么用Python写mapreduce,请举例说明,初学者,请1.lambda # 匿名函数# 基本用法 lambda x: x**2 # 第一个参数,然后是表达式# 也可以使用如下(lambda x ...

  9. python中匿名函数的作用_Python 中的匿名函数,你会用吗

    原标题:Python 中的匿名函数,你会用吗 概念 我们从一个例子引入. 这里有一个元素为非空字符串的列表,按字符串最后一个字母将列表进行排序.如果原列表是 ['abc', 'g', 'def'],则 ...

最新文章

  1. android 崩溃搜索 AndroidRuntime
  2. Eclipse-Java代码规范和质量检查插件-SonarLint
  3. php收集radio表单,jQuery对于单选表单(radio)以及其它表单取值
  4. QT精彩实例分析第5章-0
  5. asp.net中各种类型文件解析 收藏
  6. JAVA Drp项目实战—— Unable to compile class for JSP 一波三折
  7. 计算机组装与维修预习,《计算机组装与维修》预习报告、实习报告撰写要求.docx...
  8. html盒子模型页面居中,【静态页面架构】CSS之盒子模型
  9. linux中符号链接啥意思,linux – 为什么我不能在符号链接中使用“...
  10. Cannot use v-for on stateful component root element because it renders multiple elements.
  11. LeetCode 55 - 跳跃游戏
  12. python点云数据处理_python处理点云数据并生成三维点云模型
  13. java笔记框架部分
  14. 什么是计算机病毒?是怎么产生的?
  15. excel锁定某一列,不给修改
  16. photoshop cs6用户界面字体太小的解决方案
  17. 微信公众号文章怎么插附件
  18. Google Gmail Oauth Client ID 认证指南
  19. 32.我的wafBypass之道
  20. C#下Winform下使用WebKit、Geckofx、CefSharp对比及CefSharp代码实现

热门文章

  1. Shiro RememberMe
  2. TMDS 编码 解码
  3. 多多自走棋改动_多多自走棋2.0版本更新改动内容一览
  4. JVM -- 运行期优化;JIT(九)
  5. C语言实现青蛙跳台阶问题
  6. 网络IO和磁盘IO延时
  7. owl.carousel.js深入使用
  8. linux搭建sftp服务器并设置免密登录
  9. 当客户关系管理遭遇网络营销
  10. 抖音获取主播间内粉丝团用户信息