함수 안에서 static 변수를 설정하려면
조회수 14873회
C에서는 밑의 코드같이 함수 안에서 static
을 명시해줬는데
파이썬으로 함수 안에서 static
을 선언하려면 어떻게 하나요?
C코드
void foo()
{
static int counter = 0;
counter++;
printf("counter is %d\n", counter);
}
1 답변
-
질문하신 C코드와 똑같은 일을 하는 파이썬 스크립트는 다음과 같습니다.
소스코드1 - 가장 일반적인 방법
def foo(): foo.counter += 1 print "Counter is %d" % foo.counter foo.counter = 0
foo.counter = 0
이 함수의 밑이 아니라 위에 있게 하려면 다음과 같이 decorator를 만들어야 합니다.소스코드2 - decorator를 쓰는 방법
def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate @static_vars(counter=0) def foo(): foo.counter += 1 print "Counter is %d" % foo.counter
소스코드3 - 예외처리를 이용하는 방법
def foo(): try: foo.counter += 1 except AttributeError: foo.counter = 1 finally: print("Counter is %d" % foo.counter)
댓글 입력