如何在Python3中获得Closure结果

时间:2017-07-16 02:14:41

标签: python closures

我正在使用Python3,我读了“Python for Data Analysis”一书,并尝试运行以下使用 closure 的代码。

def make_closure(a):
    def closure():
        print('I know the secret: %d' % a)
    return make_closure

make_closure(5)

结果是

Out[70]: <function __main__.make_closure>

虽然这本书告诉我“所以在上面的情况下,返回的封闭将会 总是打印我知道秘密:5每当你打电话给它。“

如何将结果作为书?是因为我使用Python 3吗?

2 个答案:

答案 0 :(得分:1)

闭包需要返回内部函数,然后需要调用它,例如:

>>> def make_closure(a):
...     def closure():
...         print('I know the secret: %d' % a)
...     return closure
...
>>> secret5 = make_closure(5)
>>> secret2 = make_closure(2)
>>> secret5()
'I know the secret: 5'
>>> secret5()
'I know the secret: 5'
>>> secret2()
'I know the secret: 2'

答案 1 :(得分:1)

您需要返回closure而不是make_closureclosure闭包make_closure是创建闭包的函数:

>>> def make_closure(a):
...     def closure():
...         print('I know the secret: %d' % a)
...     return closure
... 
>>> f = make_closure(5)
>>> f()
I know the secret: 5

如果您感觉冒险,可以使用__closure__属性查看f关闭内的内容:

>>> f.__closure__[0].cell_contents
5
>>>