Iterable
- for문에서 in 뒤에 위치하여 iterate(반복, 순회)가 가능한 object
- '__iter__()' 라는 special method를 구현하고 있으며, 이를 통해 자신에 대한 iterator object을 반환할 수 있음.
collection의 object들(list, tuple, dict, set..)은 iterable object이다. collection.Iterable의 subclass.
출력
list is a subclass of Iterable True
tuple is a subclass of Iterable True
set is a subclass of Iterable True
dict is a subclass of Iterable True
Iterator
- built-in function iter()에 iteration 대상이 될 iterable object을 넘겨주거나, 해당 object의 __iter__() special method로 얻어짐.
- 자신의 special method __next__()를 통해 가지고 있는 elements에서의 iteration이 가능함. 또는 built-in function next()에 해당 iterator object를 argument로 넘겨주는 방식으로도 사용 가능.
- 모든 element가 __next__()를 통해 반환되고 나면, 이후 해당 method 호출 시 StopeIteration Exception 발생.
- iterable object과 마찬가지로 for문에서 in 뒤에 놓여져서 iteration이 가능함.
- iter(): 주어진 객체의 iterator를 반환함. 객체가 '__iter__()' 메서드를 구현하고 있으면, 'iter()'는 내부적으로 '__iter__()'메서드를 호출한다.
- 더 간단한 방식으로 iterator를 얻을 수 있도록 도와줌.
- __iter__(): 클래스 내에서 직접 구현할 수 있음. 이 메서드를 구현함으로써 해당 객체가 반복 가능한 객체(iterable)
*special method: python interpreter에 의해 간접적으로 호출되는 method. 객체의 특정 동작을 정의하기 위해 사용하는 method
- double underscore '__'로 싸여있다.
Generator
-yield(return대신 yield를 사용하여 item을 반환함)을 이용한 function으로 구현되거나, collection에 대해 yield from을 사용한 function으로 구현되거나, tuple을 이용한 comprehension을 통해 generator expression을 이용하여 구현됨.
- return은 값을 반환하고 나서 종료가 되지만, yield는 값을 반환하고 해당 함수를 종료하지 않고 상태를 그대로 유지한다.
일반적인 iterable의 경우, 해당 collection에서 가지고 있는 모든 item을 memory에 할당하여 관리하는 방식을 사용하는데, 이 경우 매우 많은 item을 가질 경우 iterable object의 memory size가 커지게 된다.
위의 단점을 해결하기 위해 제안된 것이 generator iterator이다.
generator iterator는 element를 요청받을 때 하나씩 생성하여 내보내는 iterator이다.
이로 인해 많은 양의 item을 가지는 경우에는 memory를 효율적으로 사용할 수 있다.
- 필요할 때 item을 생성하는 generator는 처음부터 다시 iteration을 하려면 generator를 다시 생성해야 된다는 단점이 있음.
'컴퓨터프로그래밍' 카테고리의 다른 글
OS Module (3) | 2024.06.03 |
---|---|
File (2) | 2024.06.03 |
Comprehension (0) | 2024.05.31 |
set, dictionary (0) | 2024.05.29 |
function (2) | 2024.05.22 |