Python3 实现 可迭代对象和 迭代器对象

[code lnag="python"]
In [1]: l = [1,2,3]

In [2]: s = 'abcdef'

In [3]: for x in l:print(x)
1
2
3

In [4]: for x in s:print(x)
a
b
c
d
e
f
# 能for 循环输出 说明是可迭代对象

In [5]: iter?
Docstring:
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator

Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
Type: builtin_function_or_method

# iter 可以从可迭代对象 --> 迭代器对象

In [6]: iter(l)
Out[6]: <list_iterator at 0x111aa44e0>
In [11]: l.__iter__() #等价于 iter(l)
Out[11]: <list_iterator at 0x111ad9940>

In [7]: iter(s)
Out[7]: <str_iterator at 0x111aae358>
In [12]: s.__iter__() # 等价于 iter(s)
Out[12]: <str_iterator at 0x111b084a8>

总结: iter先去找 __iter__ 如果没有就去找 __getitem__

Python
In [16]: ll = iter(l) In [17]: ll Out[17]: <list_iterator at 0x111b508d0> In [19]: ll.__next__() Out[19]: 1 In [20]: ll.__next__() Out[20]: 2 In [21]: ll.__next__() Out[21]: 3 In [22]: ll.__next__() --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <i<span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/python" title="View all posts in python" target="_blank">python</a></span>-input-22-1d8aafd9727f> in <module>() ----> 1 ll.__next__() StopIteration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
In [ 16 ] : ll = iter ( l )
 
In [ 17 ] : ll
Out [ 17 ] : < list_iterator at 0x111b508d0 >
 
In [ 19 ] : ll . __next__ ( )
Out [ 19 ] : 1
 
In [ 20 ] : ll . __next__ ( )
Out [ 20 ] : 2
 
In [ 21 ] : ll . __next__ ( )
Out [ 21 ] : 3
 
In [ 22 ] : ll . __next__ ( )
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
StopIteration                              Traceback ( most recent call last )
< ipython - input - 22 - 1d8aafd9727f > in < module > ( )
-- -- > 1 ll . __next__ ( )
 
StopIteration :

for 循环就是一直调用这个__next__的方法,当遇到StopIteration循环停止.




  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值