본문 바로가기
대동단결 Python

파이썬의 데코레이션 이란?

by 즐거운 지니 2023. 2. 4.
반응형

파이썬에서, 데코레이션은 함수, 클래스 또는 메소드에 추가적인 기능을 제공하기 위해 사용되는 것입니다. 데코레이터는 기존의 코드를 변경하지 않으면서, 기능을 추가하거나 향상시키는 것을 가능하게 합니다. 데코레이션은 중첩될 수 있어, 하나의 함수에 여러 개의 데코레이터를 적용할 수 있습니다.

데코레이션은 @decorator 구문을 사용하여 적용됩니다. 예를 들어, 다음은 함수에 데코레이터를 적용하는 예제입니다:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

def say_hello():
    print("hello")

say_hello = my_decorator(say_hello)

say_hello()

실행 결과:

Something is happening before the function is called.
hello
Something is happening after the function is called.

데코레이터를 사용하면, 기존의 코드를 수정하지 않고도 기능을 추가하거나 변경할 수 있어, 코드의 유지 보수성을 향상시키면서 업그레이드 할 수 있습니다.

@my_decorator
def say_hello():
    print("hello")

위의 코드에서, @my_decorator는 say_hello 함수에 my_decorator 데코레이터를 적용하는 것입니다. 실행 결과는 다음과 같습니다:

Something is happening before the function is called.
hello
Something is happening after the function is called.
반응형

댓글