【发布时间】:2017-02-24 17:02:10
【问题描述】:
在http://pythontutor.com/visualize.html 中以交互方式执行以下代码时,每次调用build_match_and_apply_functions 的框架在图形视图中显示为灰色:
这个程序用于获取单词的复数,引用自Python 3中的DIVE章节
代码:
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)
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]
def plural(noun):
for matches_rule, apply_rule in rules:
if matches_rule(noun):
return apply_rule(noun)
plural('vacancy')
问题:
1) 灰框是什么意思?它是一个仍然占用内存的闭包?
2) 我可以进入内存块吗?所以我可以在对象区域中弄清楚,所有matches_rule函数是否相同?如果它们相同,f2/f3/f4/f5 应该在那里提供模式/搜索/替换值。
如果不是,如果所有matches_rules 函数都已更改为不同的函数,则f2 3 4 5 可能会结束并消失。它们没用。
我不知道,这就是动态语言的工作原理和构建方式。
pythontutor.com ANALYZE DIGRAM 真的让我很惊讶,导师做得很好
如果你没有过期,请复制下面的链接并粘贴我的代码。我打赌你玩得很开心。
【问题讨论】:
标签: python functional-programming closures