>  기사  >  백엔드 개발  >  [Python] for 루프는 어떻게 작동하나요?

[Python] for 루프는 어떻게 작동하나요?

高洛峰
高洛峰원래의
2017-02-16 10:56:23984검색

반복적인 수준에서 이해하면 작업 방식에 대한 더 깊은 이해를 가질 수 있습니다.
먼저 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])
<list_iterator object at 0x000001A1141E0668>
>>> iter(range(0, 10))
<range_iterator object at 0x000001A1124C6BB0>
>>> iter("abc")
<str_iterator object at 0x000001A1141E0CF8>
>>>
iter函数返回的对象我们称之为iterator,iterator只需要做一件事,那就是调用next(iterator)方法,返回下一个元素。

예:

>>> t = iter("abc")
>>> next(t)
&#39;a&#39;
>>> next(t)
&#39;b&#39;
>>> next(t)
&#39;c&#39;
>>> next(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

반복자에 반복할 요소가 더 이상 없으면 예외가 발생합니다.
여기서는 itrable과 iterator의 정의를 제공합니다.
iterable:
iter에 전달될 수 있고 iteratot 객체를 반환할 수 있습니다
iterator:
다음 함수에 전달될 수 있으며 다음 반복 요소의 객체를 반환하고 끝에 예외가 발생합니다. 반복.

그래서 말씀하신 예에서는 반복자를 사용하여 재정의했습니다.

아아아아

이 글을 읽으시면서 뭔가 얻으시길 바랍니다.

[Python] for 루프 작동 방식과 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.