Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Tags
- docker-compose
- zsh
- Django
- 테라폼 기본 문법
- 도커컴포즈
- sftp란
- terraform
- docker
- linux
- DynamoDB
- server
- 빅오노테이션
- BIG-O NOTATION
- customize
- test
- AWS
- iterm2 단축키
- Shell
- iterm2 shortcuts
- nosql
- minikube 설치 방법
- 컨테이너
- Bash
- terraform 문법
- zshrc
- 테라폼 문법
- 도커
- python
- 파이썬
- minikube mac 설치
Archives
- Today
- Total
sklass의 s-class 프로그래밍 blog
Python Decorator 본문
Decorator는 해당 함수를 wrapping하고, 이 wrapping된 함수의 전처리 후처리 기능을 추가해줄 수 있게 해주는 Python의 디자인 패턴입니다.
함수 형식 Decorator 예제 코드
def greeting_decorator(func):
def my_decoration():
print("Hello")
func()
print("Bye")
return my_decoration
@greeting_decorator
def myname():
print "My name is John."
if __name__ == "__main__":
myname()
>> 'Hello'
>> 'My name is John.'
>> 'Bye'
클래스 형식 Decorator 예제 코드
decorator를 class로 사용하고 싶다면 아래와 같이 __call__ 함수로 decorator 형식을 정의해 주면된다. class의 __call__ 함수로 정의해주는게 nested 함수 형식으로 정의한 것 보다 더 깔끔해 보인다.
class GreetingDecorator:
def __init__(self, f):
self.func = f
def __call__(self, *args, **kwargs):
print("Hello")
self.func(*args, **kwargs)
print("Bye")
class MainClass:
@GreetingDecorator
def my_name_is():
print("My name is John.")
>> 'Hello'
>> 'My name is John.'
>> 'Bye'
'python' 카테고리의 다른 글
| Celery (0) | 2021.09.01 |
|---|---|
| __(double underscore) (0) | 2021.08.27 |
| @property (0) | 2021.08.26 |
| py_src 파일 구조 (0) | 2021.08.26 |
| namedtuple 사용법 (0) | 2021.08.23 |