[python]for循环是怎样工作的

如果你从迭代层面来理解的话可能对于for的工作原理会有更深的理解。首先我们来使用dir查看一下对于range、str这两个的不一样的类型有什么共同点。

>>> dir(range)
[‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’,
‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__iter__’,
‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’,
‘__repr__’, ‘__reversed__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’,
‘count’, ‘index’, ‘start’, ‘step’, ‘stop’]
>>> dir(str)
[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’,
‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__gt__’,
‘__hash__’, ‘__init__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mod__’, ‘__mul__’,
‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmod__’, ‘__rmul__’,
‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘capitalize’, ‘casefold’,
‘center’, ‘count’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘format_map’,
‘index’, ‘isalnum’, ‘isalpha’, ‘isdecimal’, ‘isdigit’, ‘isidentifier’, ‘islower’,
‘isnumeric’, ‘isprintable’, ‘isspace’, ‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’,
‘lstrip’, ‘maketrans’, ‘partition’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’,
‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’,
‘translate’, ‘upper’, ‘zfill’]
查看这两个的共有属性
>>> set(dir(range)) & set(dir(str))
{‘__hash__’, ‘__eq__’, ‘__contains__’, ‘__iter__’, ‘__getitem__’, ‘count’, ‘__lt__’,
‘__dir__’, ‘__le__’, ‘__subclasshook__’, ‘__ge__’, ‘__sizeof__’, ‘__format__’, ‘__len__’,
‘__ne__’, ‘__getattribute__’, ‘__delattr__’, ‘__reduce_ex__’, ‘__gt__’, ‘__reduce__’,
‘__setattr__’, ‘__doc__’, ‘__class__’, ‘__new__’, ‘__repr__’, ‘__init__’, ‘index’, ‘__str__’}

我们关注__iter__属性,他们两个都有这个函数,如果你查看其他可以使用for循环迭代的对象,你都可以发现这个特殊方法。实现了这个方法的对象我们称之为iterable。我们把对象传给python内置的iter()方法,会返回一个迭代器,for循环就是使用这个模式来实现适用于所有的对象。比如:

>>> iter([1, 2])

>>> iter(range(0, 10))

>>> iter(“abc”)

>>>
iter函数返回的对象我们称之为iterator,iterator只需要做一件事,那就是调用next(iterator)方法,返回下一个元素。

举例:

>>> t = iter(“abc”)
>>> next(t)
‘a’
>>> next(t)
‘b’
>>> next(t)
‘c’
>>> next(t)
traceback (most recent call last):
file “”, line 1, in
stopiteration

当迭代器再没有元素可以迭代时会引发一个异常。那么在这里我给出itrable和iterator的定义。iterable:可以传给iter并返回一个iteratot的对象iterator:可以传给next函数并返回下一个迭代元素的对象,并在迭代结束引发一个异常。

因此,对于你提的例子我们使用迭代器来重新定义一下。

>>> t = iter(range(90, 0, -1))
>>> t

>>> next(t)
90
>>> next(t)
89
>>> next(t)
88

希望看完有所收获。

更多[python] for循环是怎样工作的相关文章请关注php中文网!

Posted in 未分类

发表评论