Python中文
首页
教程
问答
标签
搜索
登录
注册
如何重写Python列表(迭代器)行为?
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>运行此:</p> <pre><code>class DontList(object): def __getitem__(self, key): print 'Getting item %s' % key if key == 10: raise KeyError("You get the idea.") return None def __getattr__(self, name): print 'Getting attr %s' % name return None list(DontList()) </code></pre> <p>产生这个:</p> <pre><code>Getting attr __length_hint__ Getting item 0 Getting item 1 Getting item 2 Getting item 3 Getting item 4 Getting item 5 Getting item 6 Getting item 7 Getting item 8 Getting item 9 Getting item 10 Traceback (most recent call last): File "list.py", line 11, in <module> list(DontList()) File "list.py", line 4, in __getitem__ if key == 10: raise KeyError("You get the idea.") KeyError: 'You get the idea.' </code></pre> <p>我怎样才能改变它,这样我就可以得到<code>[]</code>,同时仍然允许访问那些键<code>[1]</code>等等。?</p> <p>(我试过放入<code>def __length_hint__(self): return 0</code>,但没有帮助。)</p> <p><strong>我的真实用例:</strong>(如果有用的话,请仔细阅读;可以忽略这一点)</p> <p>在将<a href="http://code.google.com/p/iniparse/issues/detail?id=25">a certain patch</a>应用到InParse之后,我发现我的补丁有一个令人讨厌的副作用。在我的类上设置<code>__getattr__</code>,它返回一个新的<code>Undefined</code>对象。不幸的是,这意味着<code>list(iniconfig.invalid_section)</code>(其中<code>isinstance(iniconfig, iniparse.INIConfig)</code>)正在这样做(在<code>__getattr__</code>和<code>__getitem__</code>中放入简单的<code>print</code>):</p> <pre><code>Getting attr __length_hint__ Getting item 0 Getting item 1 Getting item 2 Getting item 3 Getting item 4 </code></pre> <p>等等。</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>如果要重写迭代,那么只需在类中定义<code>__iter__</code>方法</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
plt.savefig不会覆盖现有文件
9 回答
plt.savefig不保存图像
1 回答
plt.savefig在jupyter笔记本中不起作用
6 回答
plt.savefig在从另一个fi调用时停止工作
5 回答
plt.savefig在调用plt.show之前保存空数字
7 回答
plt.save不创建png文件
1 回答
plt.scatter overlay分类数据帧列
1 回答
Plt.Scatter:如何添加title、xlabel和ylab
10 回答
plt.scatter()绘图与Matplotlib中的plt.plot()绘图类似
8 回答
plt.scatter错误'NoneType'对象在成功运行后没有属性'sqrt'
7 回答
plt.set_title()中的标题字符串有误
2 回答
plt.show()
1 回答
plt.show()不在Jupyter笔记本上渲染任何内容
7 回答
plt.show()不打印plt.plot only plt.scatter
1 回答
plt.show()不显示三维散射图像
7 回答
plt.show()不显示任何内容
4 回答
plt.show()不显示数据,而是保留它供下一个图表使用(spyder)
3 回答
plt.show()使终端挂起
4 回答
plt.show()无法使用此代码
2 回答
plt.show()没有打开新的图形风
7 回答