第6章 CLOSURES & GENERATORS

第6章 CLOSURES & GENERATORS

(1)Closures——封闭

import re
def build_match_and_apply_functions(pattern, search, replace):①
   def matches_rule(word):
     return re.search(pattern, word)
   def apply_rule(word): ②
     return re.sub(search, replace, word)
   return (matches_rule, apply_rule) ③

  1. build_match_and_apply_functions可以动态的建立函数,它有三个参数pattern, search, replace。
  2. word参数是一个外部变量,这种在动态函数中使用外部参数变量的技术叫做“closures
  3. build_match_and_apply_functions函数返回一个元组,元组中有两个函数,分别是matches_rule和apply_rule,这两个函数中使用的pattern, search和replace参数都来自build_match_and_apply_functions函数的参数列表,而word来自外部,也就是最终使用的时候传递。

初始化pattern, search和replace:

patterns = \ ①
(
('[sxz]$','$','es'),('[^aeioudgkprt]h$','$','es'),('(qu|[^aeiou])y$','y$','ies'),
('$','$','s') ②
)
rules = [build_match_and_apply_functions(pattern, search, replace)
for (pattern, search, replace) in patterns]③

  1. 初始化patterns
  2. 未匹配到的单词默认行为加s
  3. 这是一个list comprehension,首先 (pattern, search, replace)从patterns中得到值,然后通过build_match_and_apply_functions(pattern, search, replace)返回的元组建立list。

最后使用的时候:

def plural(noun): ①
   for matches_rule, apply_rule in rules:
     if matches_rule(noun):
   return apply_rule(noun)

这是一个单词分析程序,把名词单数形式变成复数形式。

(2)Generators——生成器

def make_counter(x):
   print('entering make_counter')
   while True:
     yield x          ①
     print('incrementing x')
     x = x + 1

counter = make_counter(2)              ②
counter                                                         ③
<generator object at 0x001C9C10>
next(counter)                                            ④
entering make_counter
2
next(counter)                                            ⑤
incrementing x
3
next(counter)                                          
incrementing x
4

  1. yield指明这是一个很特别的程序,yield可以记住某些值。
  2. 建立一个生成器实例
  3. counter就是make_counter()的实例
  4. next()函数使生成器返回下一个值。每次执行都会执行到yield语句,然后yield会返回当前值。本例第一次执行会返回2。
  5. 再次执行时,依然如此,顺序向下执行代码,和其它程序段没有区别。
  6. yield暂停一个程序段,next()恢复上一次暂停位置的程序段,如果函数已经到了结尾,继续使用next()会引发一个StopIterator的异常。

发表回复