你能解释闭包(因为它们与Python有关)? [英] Can you explain closures (as they relate to Python)?
本文介绍了你能解释闭包(因为它们与Python有关)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经阅读了很多关于闭包,我认为我理解他们,但没有为自己和其他人遮掩的图片,我希望有人可以解释闭包,尽可能简洁和清晰。我正在寻找一个简单的解释,可能会帮助我了解在哪里和为什么要使用它们。
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
推荐答案
对象是方法
附加的数据,闭包是附加了
数据的函数。
Objects are data with methods attached, closures are functions with data attached.
def make_counter():
i = 0
def counter(): # counter() is a closure
nonlocal i
i += 1
return i
return counter
c1 = make_counter()
c2 = make_counter()
print (c1(), c1(), c2(), c2())
# -> 1 2 1 2
这篇关于你能解释闭包(因为它们与Python有关)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文