Skip to content
Minsing Log
Go back

English Edition

What is a decorator (@)?

Programming & CS

Conclusion

It literally means decorating a function; you can think of it as the concept of composite functions that we learned in mathematics. Awesome explanation 1 Awesome explanation 2

Decorators are used to implement additional functionality without modifying existing functions.

Decorator = trace function Existing function = hello, world function

def trace(func):                             # 호출할 함수를 매개변수로 받음
    def wrapper():                           # 호출할 함수를 감싸는 함수
        print(func.__name__, '함수 시작')    # __name__으로 함수 이름 출력
        func()                               # 매개변수로 받은 함수를 호출
        print(func.__name__, '함수 끝')
    return wrapper                           # wrapper 함수 반환
 
def hello():
    print('hello')
 
def world():
    print('world')
 
trace_hello = trace(hello)    # 데코레이터에 호출할 함수를 넣음
trace_hello()                 # 반환된 함수를 호출
trace_world = trace(world)    # 데코레이터에 호출할 함수를 넣음
trace_world()           

Cases where @ is used

def trace(func):                             # 호출할 함수를 매개변수로 받음
    def wrapper():
        print(func.__name__, '함수 시작')    # __name__으로 함수 이름 출력
        func()                               # 매개변수로 받은 함수를 호출
        print(func.__name__, '함수 끝')
    return wrapper                           # wrapper 함수 반환
 
@trace    # @데코레이터
def hello():
    print('hello')
 
@trace    # @데코레이터
def world():
    print('world')
 
hello()    # 함수를 그대로 호출
world()    # 함수를 그대로 호출

Principle

A decorator takes the form of wrapping a function.

Note -> You can also specify multiple decorators.

@데코레이터1
@데코레이터2
def 함수이름():
    코드

References https://dojang.io/mod/page/view.php?id=2427

Follow the journey

Get new posts by email.

Short, honest notes on building, startups, learning, failures, and retrospectives, for readers who follow the journey rather than pass through from search.

The newsletter is coming soon. Until then, follow via RSS or email me to get notified.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
Wrong Abstraction
Next Post
What Is Abstraction?