[Python기초] 11. 람다, pass, __doc__속성과 help, 이터레이터 객체
람다(lambda)
- 익명 함수를 만들 때
- 파이썬에서는 함수의 이름이 없는 바디만 정의한 익명함수를 만들 수 있음
- 일반 함수와 마찬가지로 여러 개의 인자를 전달 받을 수 있음
- return 구문을 적지 않아도 반환값을 돌려줄 수 있음
lamda 인자: <구문>
>>> g = lambda x, y: x*y
>>> g(2, 3)
6
>>> (lambda x: x*x)(3)
9
>>>globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'g': <function <lambda> at 0x041C8850>}
pass
- 아무것도 하지않고 그냥 넘어가도록 할 때
- pass 키워드를 사용해서 함수, 모듈, 클래스의 내부를 채울 수 있음
>>> while True:
pass # 빠져 나가려면 키보드에서 "ctrl + c"를 누름
KeyboardInterrupt
>>>
>>>
>>> class temp:
pass
doc, help
- doc
- 생성한 함수의 설명을 추가하고 싶을 때
>>> def add(a, b): return a + b >>> add.__doc__ = "이 함수는 2개의 인자를 받아서 덧셈을 수행하는 함수입니다." >>> help(add) Help on function add in module __main__: add(a, b) 이 함수는 2개의 인자를 받아서 덧셈을 수행하는 함수입니다.
- help()
- 함수의 도움말을 보고 싶을 때
>>> help(print) Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
이터레이터
- 순회 가능한 형식에서 값을 안전하고 빠르게 나열하고 싶을 때
- 리스트, 튜플, 문자열처럼 순회가능한 시퀀스 형식에는 구현되어 있음
>>> for element in [1, 2, 3]:
print(element)
>>> for element in (1, 2, 3):
print(element)
>>> for key in {'one': 1, 'two': 2}:
print(key)
>>> for char in "123":
print(char)
>>> s = 'abc'
>>> it = iter(s)
>>> it
<str_iterator object at 0x00F121A8>
>>> next(it)
'a'