-
파이썬 - docstringpython 2021. 3. 19. 20:31
'가독성은 중요하다readability counts'라는 구절은 파이썬의 철학(www.python.org/dev/peps/pep-0020/)에 들어있는 구문이다. 함수의 docstring을 이용해서 함수 몸체 시작 부분에 문자열을 포함시켜 함수 정의에 문서(documentation)를 붙일 수 있다.
>>> def echo(anything): ... 'echo returns its input argument' ... return anything
docstring은 길게 작성할 수 있으며, 서식(formatting)을 추가할 수도 있다.
def print_if_true(thing, check): ''' Prints the first argument if a second argument is true. The operation is: 1. Check whether the *second* argument is true. 2. If it is, print the *first* argument. ''' if check: print(thing)
함수의 docstring을 출력하려면 help() 함수를 호출한다. 함수 인자의 리스트와 서식화된 docstring을 읽기 위해 함수 이름을 인자로 전달한다.
>>> help(echo) Help on function echo in module __main__: echo(anything) echo returns its input argument
만약 서식 없는 docstring을 그대로 보고 싶다면 다음과 같이 한다.
>>> print(echo.__doc__) echo returns its input argument
출처: Introducing python
'python' 카테고리의 다른 글
파이썬 - News categorization (0) 2021.03.22 파이썬 - 제너레이터 / 데커레이터 (0) 2021.03.19 파이썬 - 이터레이터 (0) 2021.03.18 파이썬 - 람다 함수 (0) 2021.03.16 파이썬 - 인수(argument) (0) 2021.03.16