
Lazy Evaluation : 파이썬의 객체지향Language/Python2024. 8. 22. 07:59
Table of Contents
Lazy Evaluation이란?
In programming language theory, lazy evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (by the use of sharing). -Lazy Evaluation, wikipedia
Lazy Evaluation은 계산 결괏값이 필요할 때까지 계산을 늦추는 기법으로, 파이썬 뿐만 아니라 전반적인 컴퓨터 프로그래밍에서 쓰이는 용어이다.
실행과 동시에 구현하여 메모리에 보관하는 것이 아닌, 이터러블한 객체로 생성하여 필요할 때 그때그때 값을 만들어서 보내주는 형식을 의미한다.
반복문 등을 통해서만 요소를 하나씩 접근할 수 있다.
예시 코드
zip 객체
z = zip([1, 2, 3], ['a', 'b', 'c'])
print(z) # <zip object at 0x...>
print(next(z)) # (1, 'a')
print(next(z)) # (2, 'b')
print(next(z)) # (3, 'c')
z = zip([1, 2, 3], ['a', 'b', 'c'])
for i in z:
print(i) # [(1, 'a'), (2, 'b'), (3, 'c')]
print(list(z)) # []
enumerate 객체
names = ["Sarah", "Matt", "Jim", "Denise", "Kate"]
# enumerate
numbered_names = enumerate(names, start=1)
print(numbered_names) # <enumerate object at 0x...
for index, name in numbered_names:
print(f"{index}. {name}")
map 객체
m = map(str.upper, ['a', 'b', 'c'])
print(m) # <map object at 0x...>
print(list(m)) # ['A', 'B', 'C']
range 객체
r = range(1, 10)
print(r) # range(1, 10)
print(list(r)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
요약
이러한 객체들은 메모리 효율성을 위해 사용되며, 직접 출력할 때는 메모리 주소만 표시된다.
이를 통해 모든 요소를 메모리에 로드하지 않고도 데이터를 처리할 수 있다.
값을 확인하려면 반복문을 사용하거나 list() 또는 next()와 같은 함수를 사용해 접근해야 한다.
이러한 문법은 "파이썬에서는 모든 것이 객체이다"라는 설명을 보충설명할 수 있다.
'Language > Python' 카테고리의 다른 글
Python에서 .env 환경변수 파일 작성 및 관리 (0) | 2024.10.31 |
---|---|
파이썬 : Closure(클로저), Currying(커링) (3) | 2024.09.07 |
@def__init__ :: KeepGoing!
개발새발라이프
hi there🙌