欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python for循环与getitem的关系详解

时间:2021-06-28 08:25:51|栏目:Python代码|点击:

这篇文章主要介绍了Python for循环与getitem的关系详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

一个类里面如果由__iter__for循环就是找它取,没有的话就会找__getitem__

前面一笔看过没有留心具体的执行情况。

In [169]: class Foo:
   ...:   def __getitem__(self, pos):
   ...:     print(pos)
   ...:     return range(10)[pos]
   ...:  
In [172]: for i in f:
   ...:   ...
   ...:   
   ...:                                             
0
1
2
3
4
5
6
7
8
9
10

从代码可以看出,如果没有报错或者设置显式的条件,这个for循环会无线循环。

我现在设置一个显式的设置。

In [173]: class Foo:
   ...:   def __getitem__(self, pos):
   ...:     if pos >5:
   ...:       raise StopIteration
   ...:     print(pos)
   ...:     return range(10)[pos]
   ...: 
In [177]: for i in f:
   ...:   ...
   ...:                                             
0
1
2
3
4
5

将错误设置为IndexError也可以执行,但TypeError就不行了。

   ...:   def __getitem__(self, pos):
   ...:     if pos >5:
   ...:       raise IndexError
   ...:     print(pos)
   ...:     return range(10)[pos]
   ...:                                             
 
In [182]:                                             
 
In [182]: f = Foo()                                        
 
In [183]: for i in f:
   ...:   ...
   ...:                                             
0
1
2
3
4
5

如果用list去运行这个参数会把返回的一个一个元素,装入列表当中:

In [184]: list(f)                                         
0
1
2
3
4
5
Out[184]: [0, 1, 2, 3, 4, 5]

只有__getitem__的类的实例是属于可迭代对象,但用isinstances测试collections.Iterable是不能通过的,书后面介绍可以通过iter函数来测试,如果没报错就说明是可迭代对象,然后生成一个没有__next__属性的迭代器。

In [185]: from collections import Iterable                            
In [186]: isinstance(f, Iterable)                                 
Out[186]: False
 
In [187]: iter(f)                                         
Out[187]: <iterator at 0x114f2be50>
dir(f)                                         
Out[189]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']

上一篇:python实现查找excel里某一列重复数据并且剔除后打印的方法

栏    目:Python代码

下一篇:基于python判断目录或者文件代码实例

本文标题:Python for循环与getitem的关系详解

本文地址:http://www.codeinn.net/misctech/149291.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有