Python中文
首页
教程
问答
标签
搜索
登录
注册
嵌套函数中的局部变量
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>好吧,请原谅我,我知道这看起来很复杂,但请帮助我理解发生了什么。</p> <pre><code>from functools import partial class Cage(object): def __init__(self, animal): self.animal = animal def gotimes(do_the_petting): do_the_petting() def get_petters(): for animal in ['cow', 'dog', 'cat']: cage = Cage(animal) def pet_function(): print "Mary pets the " + cage.animal + "." yield (animal, partial(gotimes, pet_function)) funs = list(get_petters()) for name, f in funs: print name + ":", f() </code></pre> <p>给出:</p> <pre><code>cow: Mary pets the cat. dog: Mary pets the cat. cat: Mary pets the cat. </code></pre> <p>所以基本上,为什么我没有三种不同的动物?不是将<code>cage</code>“打包”到嵌套函数的本地作用域中吗?如果不是,对嵌套函数的调用如何查找局部变量?</p> <p>我知道遇到这些问题通常意味着一个人“做错了”,但我想知道会发生什么。</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>这源于以下原因</p> <pre><code>for i in range(2): pass print i is 1 </code></pre> <p>迭代后<code>i</code>的值被延迟存储为其最终值。</p> <p>作为生成器,该函数可以工作(即依次打印每个值),但是当转换为列表时,它在生成器上运行,因此对<code>cage</code>(<code>cage.animal</code>)的所有调用都返回cats。</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何在python中从数据帧列中删除分类值?
2 回答
如何在python中从数据帧列表中删除引号
1 回答
如何在python中从数据帧创建列表
3 回答
如何在Python中从数据帧创建嵌套的JSON
4 回答
如何在Python中从数据帧显示wordcloud
1 回答
如何在Python中从数据帧的时间戳中删除字符
10 回答
如何在Python中从数据帧绘制简单绘图?
8 回答
如何在python中从数据帧行提取具有特定长度的范围?
10 回答
如何在python中从数据帧设置dict中的值
6 回答
如何在Python中从数据库中获得一个结果
8 回答
如何在python中从数据框中绘制分类条形图
4 回答
如何在Python中从数据框中选择特定细节?
9 回答
如何在python中从数据集中删除unicode
6 回答
如何在python中从数据集中删除某些数值?
9 回答
如何在python中从数据集中选择行
9 回答
如何在Python中从数组中删除元素
7 回答
如何在python中从数组中删除单个倒逗号?
3 回答
如何在python中从数组中删除对象?
4 回答
如何在python中从数组中删除引号
7 回答
如何在python中从数组中删除所有最小值
9 回答