Python for循环与getitem的关系详解

yipeiwu_com6年前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设计】。

相关文章

爬山算法简介和Python实现实例

一、爬山法简介 爬山法(climbing method)是一种优化算法,其一般从一个随机的解开始,然后逐步找到一个最优解(局部最优)。 假定所求问题有多个参数,我们在通过爬山法逐步获得最...

Python中的list与tuple集合区别解析

Python中内置了list集合与tuple集合,在list集合中可以实现元素的添加、修改、插入、以及删除。tuple集合看似与list类似,但两者还是有很大的区别。 在tuple集合中...

Python中让MySQL查询结果返回字典类型的方法

Python的MySQLdb模块是Python连接MySQL的一个模块,默认查询结果返回是tuple类型,只能通过0,1..等索引下标访问数据 默认连接数据库: 复制代码 代码如下: M...

python批量图片处理简单示例

本文实例讲述了python批量图片处理。分享给大家供大家参考,具体如下: #!/usr/bin/python #coding:utf-8 import os from PIL imp...

django formset实现数据表的批量操作的示例代码

什么是formset 我们知道forms组件是用来做表单验证,更准确一点说,forms组件是用来做数据库表中一行记录的验证。有forms组件不同,formset是同科同时验证表中的多行...