본문 바로가기
기술스택을 쌓아보자/Python

[python] staticmethod, classmethod 데코레이터 여러개 쓰기AttributeError: 'staticmethod' object has no attribute '__module__'/

by 소리331 2022. 5. 18.
반응형

작은 에러는 함께 깨부셔보아요

 

데코레이터는 간단하게 아래처럼 중첩해서 사용하면 된다.

@decor1
@decor
def num():
    statement(s)   

 

그런데~ 아무생각 없이 @staticmethod와 중첩해서 사용하니 에러가 발생했다.

 

 

@staticmethod @classmethod와 중첩시 유의점

 

  • @staticmethod @classmethod가 바깥에 와야한다(먼저) 안그러면 아래와 같은 AttributeError가 발생한다. 

 

Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/opt/conda/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/hoseung2/.local/lib/python3.6/site-packages/memory_profiler.py", line 1349, in <module>
    exec_with_profiler(script_filename, prof, args.backend, script_args)
  File "/home/hoseung2/.local/lib/python3.6/site-packages/memory_profiler.py", line 1250, in exec_with_profiler
    exec(compile(f.read(), filename, 'exec'), ns, ns)
...
  File "/home/hoseung2/.local/lib/python3.6/site-packages/memory_profiler.py", line 1186, in wrapper
    val = prof(func)(*args, **kwargs)
  File "/home/hoseung2/.local/lib/python3.6/site-packages/memory_profiler.py", line 715, in __call__
    f.__module__ = func.__module__
AttributeError: 'staticmethod' object has no attribute '__module__'

 

 

왜 이렇게 써야할까?

 

  • 적용순서: inner -> outer, 데코레이터는 안쪽에 있는 것부터 바깥쪽으로 작용한다.
  • descriptor: 다른 데코레이터와 달리 classmethod와 staticmethod는 descriptor를 반환한다.
  • 때문에 classmethod와 staticmethod 적용 시 이 둘을 가장 top!!! outer!!! 에 배치하자!

 

참고자료

 

디스크립터 사용법 안내서 — Python 3.10.4 문서

저자 Raymond Hettinger 연락처 디스크립터는 객체가 어트리뷰트 조회, 저장 및 삭제를 사용자 정의 할 수 있도록 합니다. 이 지침서는 네 개의 주요 섹션으로 구성됩니다: “입문”은 간단한 예제에

docs.python.org

 

 

 

Why can @decorator not decorate a staticmethod or a classmethod?

Why can decorator not decorate a staticmethod or a classmethod? from decorator import decorator @decorator def print_function_name(function, *args): print '%s was called.' % function.func_nam...

stackoverflow.com

 

Chain Multiple Decorators in Python - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

반응형

댓글