因此,我正在阅读这个精彩的作品,它试图解释python中的装饰器。
我的问题是针对这个代码片段的。
def surround_with(surrounding):
"""Return a function that takes a single argument and."""
def surround_with_value(word):
return '{}{}{}'.format(surrounding, word, surrounding)
return surround_with_value
def transform_words(content, targets, transform):
"""Return a string based on *content* but with each occurrence
of words in *targets* replaced with
the result of applying *transform* to it."""
result = ''
for word in content.split():
if word in targets:
result += ' {}'.format(transform(word))
else:
result += ' {}'.format(word)
return result
markdown_string = 'My name is Jeff Knupp and I like Python but I do not own a Python'
markdown_string_italicized = transform_words(markdown_string, ['Python', 'Jeff'],
surround_with('*'))
print(markdown_string_italicized)我不明白的是,函数surround_with()是如何在它的作用域中获得变量word (当transform(word)在transform_words()中传递时)的?我的意思是,我们只声明了一个保持变量(作为函数参数),用于周围的值应该是什么,而没有其他任何东西。那么word是如何提供给它的?
我在这里错过了什么?
发布于 2016-07-14 09:00:46
surround_with()函数返回另一个带有闭包的函数对象
def surround_with(surrounding):
"""Return a function that takes a single argument and."""
def surround_with_value(word):
return '{}{}{}'.format(surrounding, word, surrounding)
return surround_with_value因此,返回surround_with_value;是这个函数将surrounding的值添加到传入的任何内容中:
>>> def surround_with(surrounding):
... """Return a function that takes a single argument and."""
... def surround_with_value(word):
... return '{}{}{}'.format(surrounding, word, surrounding)
... return surround_with_value
...
>>> function = surround_with(' foo ')
>>> function
<function surround_with_value at 0x108ac16e0>
>>> function('bar')
' foo bar foo '返回surround_with_value()函数,并将对其的引用存储在名称function中。该函数对象将surrounding引用为闭包。
>>> function.__closure__
(<cell at 0x108a8a590: str object at 0x1074c4060>,)
>>> function.__closure__[0].cell_contents
' foo '每次你称它为闭包被取消引用和内容被使用。
因此,surround_with()生成一个函数对象,该函数(作为surround_with('*')的结果)作为第三个参数传递给transform_words():
transform_words(markdown_string, ['Python', 'Jeff'],
surround_with('*'))因此它被赋值给变量transform。
def transform_words(content, targets, transform):因此,每次调用transform时,实际上都是以'*'作为surrounding闭包调用嵌套的surrounding函数,并传入word:
result += ' {}'.format(transform(word))发布于 2016-07-14 08:59:33
我想我明白了,
当我们调用surround_with('*')时,它返回函数surround_with_value(),然后返回值'{}{}{}'.format('*', word, '*')。
现在,相同的函数接受一个参数(此处为word),然后在transform_words()中传递该参数,并将其重命名为transform()。
在它中,我们最终传递了word的值。
发布于 2016-07-15 19:55:28
闭包可能非常令人困惑,这个示例可能不是向展示为什么 surround_with_value() 会记住在其作用域内的环绕事件的原因。
我强烈建议你阅读这个优秀的博客,展示你需要理解的所有概念来理解装饰师。Step1:范围->步骤2:闭包->步骤3:装饰器
花点时间从一开始就读一读。http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/
https://stackoverflow.com/questions/38369575
复制相似问题