deflog(message,when=datetime.now()):print("%s: %s"%(when,message))log("Hi there!")sleep(0.1)log("Hi again!")>>>2014-11-1521:10:10.371432:Hithere!# 타임스탬프 동일하게 출력2014-11-1521:10:10.371432:Hiagain!
datetime.now는 함수를 정의할 때 딱 한 번만 실행: 타임스탬프 동일하게 출력
이 코드를 담고 있는 모듈이 로드된 후에는 기본 인수인 datetime.now를 다시 평가하지 않음
결과가 기대한 대로 나오게 하려면 기본값을 None으로 설정하고 docstring(문서화 문자열)으로 실제 동작을 문서화하는 것이 관례
“WAY 49. 모든 함수, 클래스, 모듈에 docstring을 작성하자” 참고
코드에서 None이 나타나면 알맞은 기본값을 할당하면 됨
deflog(message,when=None):""" Log a message with a timestamp.
Args:
message: Message to print.
when: datetime of when the message occurred.
Defaults to the present time.
"""when=datetime.now()ifwhenisNoneelsewhenprint("%s: %s"%(when,message))log("Hi there!")sleep(0.1)log("Hi again!")>>>2014-11-1521:10:10.4772303:Hithere!# 타임스탬프 다르게 출력2014-11-1521:10:10.5773395:Hiagain!
Comments