... 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.