目录 | 上一节 (7.2 匿名函数) | 下一节 (7.4 装饰器)python
本节介绍使用函数建立其它函数的思想。git
考虑如下函数:github
def add(x, y): def do_add(): print('Adding', x, y) return x + y return do_add
这是返回其它函数的函数。segmentfault
>>> a = add(3,4) >>> a <function do_add at 0x6a670> >>> a() Adding 3 4 7
请观察内部函数是如何引用外部函数定义的变量的。闭包
def add(x, y): def do_add(): # `x` and `y` are defined above `add(x, y)` print('Adding', x, y) return x + y return do_add
进一步观察会发现,在 add()
函数结束后,这些变量仍然保持存活。函数
>>> a = add(3,4) >>> a <function do_add at 0x6a670> >>> a() Adding 3 4 # Where are these values coming from? 7
当内部函数做为结果返回时,该内部函数称为闭包(closure)。ui
def add(x, y): # `do_add` is a closure def do_add(): print('Adding', x, y) return x + y return do_add
基本特性:闭包保留该函数之后正常运行所需的全部变量的值。能够将闭包视做一个函数,该函数拥有一个额外的环境来保存它所依赖的变量的值。翻译
虽然闭包是 Python 的基本特性,可是它们的用法一般很微妙。常见应用:code
考虑这样的函数:get
def after(seconds, func): import time time.sleep(seconds) func()
使用示例:
def greeting(): print('Hello Guido') after(30, greeting)
after
(延迟30 秒后)执行给定的函数......
闭包附带了其它信息。
def add(x, y): def do_add(): print(f'Adding {x} + {y} -> {x+y}') return do_add def after(seconds, func): import time time.sleep(seconds) func() after(30, add(2, 3)) # `do_add` has the references x -> 2 and y -> 3
闭包也能够用做一种避免代码大量重复的技术。
闭包的一个更强大的特性是用于生成重复的代码。让咱们回顾 练习 5.7 代码,该代码中定义了带有类型检查的属性:
class Stock: def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price ... @property def shares(self): return self._shares @shares.setter def shares(self, value): if not isinstance(value, int): raise TypeError('Expected int') self._shares = value ...
与其一遍又一遍地输入代码,不如使用闭包自动建立代码。
请建立 typedproperty.py
文件,并把下述代码放到文件中:
# typedproperty.py def typedproperty(name, expected_type): private_name = '_' + name @property def prop(self): return getattr(self, private_name) @prop.setter def prop(self, value): if not isinstance(value, expected_type): raise TypeError(f'Expected {expected_type}') setattr(self, private_name, value) return prop
如今,经过定义下面这样的类来尝试一下:
from typedproperty import typedproperty class Stock: name = typedproperty('name', str) shares = typedproperty('shares', int) price = typedproperty('price', float) def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price
请尝试建立一个实例,并验证类型检查是否有效:
>>> s = Stock('IBM', 50, 91.1) >>> s.name 'IBM' >>> s.shares = '100' ... should get a TypeError ... >>>
在上面示例中,用户可能会发现调用诸如 typedproperty('shares', int)
这样的方法稍微有点冗长 ——尤为是屡次重复调用的时候。请将如下定义添加到 typedproperty.py
文件中。
String = lambda name: typedproperty(name, str) Integer = lambda name: typedproperty(name, int) Float = lambda name: typedproperty(name, float)
如今,请从新编写 Stock
类以使用如下函数:
class Stock: name = String('name') shares = Integer('shares') price = Float('price') def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price
啊,好一点了。这里的要点是:闭包和 lambda
经常使用于简化代码,并消除使人讨厌的代码重复。这一般很不错。
请从新编写 stock.py
文件中的 Stock
类,以便使用上面展现的类型化特性(typed properties)。