Skip to Content
Python语言及其应用(第2版)
book

Python语言及其应用(第2版)

by Bill Lubanovic
March 2022
Intermediate to advanced
522 pages
13h 52m
Chinese
Posts & Telecom Press
Content preview from Python语言及其应用(第2版)
132
9
之外创建的变量的值。
下面的例子以之前的
knights()
示例为基础。我们将其称为
knights2()
(原谅我们在起名
字方面实在缺乏想象力),另外将
inner()
函数变成闭包
inner2()
。不同之处如下:
inner2()
会直接使用外围的形参
saying
,而不是将其作为参数;
knights2()
会返回函数名称
inner2
,而不是调用该函数。
>>> def knights2(saying):
... def inner2():
... return "We are the knights who say: '%s'" % saying
... return inner2
...
inner2()
函数知道传入的
saying
的值并会记录下来。
return inner2
会返回
inner2
函数的
特殊副本(但不会调用它)。这就是闭包:一个动态创建的函数,能够记住创建时所在的
环境。
下面来使用不同的参数连续调用
knights2()
两次:
>>> a = knights2('Duck')
>>> b = knights2('Hasenpfeffer')
a
b
会包含什么内容?
>>> type(a)
<class 'function'>
>>> type(b)
<class 'function'>
两者都是函数,同时也是闭包:
>>> a
<function knights2.<locals>.inner2 at 0x10193e158>
>>> b
<function knights2.<locals>.inner2 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
Python技术基础视频教程

Python技术基础视频教程

保罗·J·戴特尔
Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott

Publisher Resources

ISBN: 9787115586223