首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python装饰器中将变量范围传递给另一个函数时

在python装饰器中将变量范围传递给另一个函数时
EN

Stack Overflow用户
提问于 2016-07-14 08:48:24
回答 3查看 66关注 0票数 0

因此,我正在阅读这个精彩的作品,它试图解释python中的装饰器。

我的问题是针对这个代码片段的。

代码语言:javascript
复制
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是如何提供给它的?

我在这里错过了什么?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-07-14 09:00:46

surround_with()函数返回另一个带有闭包的函数对象

代码语言:javascript
复制
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的值添加到传入的任何内容中:

代码语言:javascript
复制
>>> 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引用为闭包。

代码语言:javascript
复制
>>> function.__closure__
(<cell at 0x108a8a590: str object at 0x1074c4060>,)
>>> function.__closure__[0].cell_contents
' foo '

每次你称它为闭包被取消引用和内容被使用。

因此,surround_with()生成一个函数对象,该函数(作为surround_with('*')的结果)作为第三个参数传递给transform_words()

代码语言:javascript
复制
transform_words(markdown_string, ['Python', 'Jeff'],
        surround_with('*'))

因此它被赋值给变量transform

代码语言:javascript
复制
def transform_words(content, targets, transform):

因此,每次调用transform时,实际上都是以'*'作为surrounding闭包调用嵌套的surrounding函数,并传入word

代码语言:javascript
复制
result += ' {}'.format(transform(word))
票数 1
EN

Stack Overflow用户

发布于 2016-07-14 08:59:33

我想我明白了,

当我们调用surround_with('*')时,它返回函数surround_with_value(),然后返回值'{}{}{}'.format('*', word, '*')

现在,相同的函数接受一个参数(此处为word),然后在transform_words()中传递该参数,并将其重命名为transform()

在它中,我们最终传递了word的值。

票数 0
EN

Stack Overflow用户

发布于 2016-07-15 19:55:28

闭包可能非常令人困惑,这个示例可能不是向展示为什么 surround_with_value() 会记住在其作用域内的环绕事件的原因。

我强烈建议你阅读这个优秀的博客,展示你需要理解的所有概念来理解装饰师。Step1:范围->步骤2:闭包->步骤3:装饰器

花点时间从一开始就读一读。http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38369575

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档