Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
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 29 30
Tags
more
Archives
Today
Total
관리 메뉴

파이썬 공부하기

[Python] 파이썬 데코레이터(Decorator) 본문

파이썬 중급

[Python] 파이썬 데코레이터(Decorator)

파이썬러버 2024. 1. 14. 03:19

데코레이터(Decorator)는 파이썬에서 함수나 메서드의 동작을 수정하거나 확장할 수 있는 기능입니다. 데코레이터는 @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

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

위의 예제에서 @my_decorator 라인은 say_hello 함수를 my_decorator 함수로 데코레이트하는 것을 나타냅니다. 이렇게 하면 say_hello 함수가 호출될 때 my_decorator 함수 내의 코드도 함께 실행됩니다.

데코레이터는 함수나 메서드에 적용되기 전에 정의되어야 합니다. 여러 개의 데코레이터를 적용할 수 있으며, 적용 순서는 위에서 아래로입니다.

@decorator1
@decorator2
@decorator3
def my_function():
    # 함수의 본문

위의 코드에서 my_function 함수는 decorator1(decorator2(decorator3(my_function))) 순서로 데코레이트됩니다.

매개변수를 받는 데코레이터

데코레이터는 매개변수를 받도록 구성될 수 있습니다. 이때는 추가로 한 번 더 함수를 감싸는 형태로 작성됩니다.

def decorator_with_args(arg):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print(f"Decorator arguments: {arg}")
            func(*args, **kwargs)
        return wrapper
    return decorator

@decorator_with_args("example")
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("Alice")

위의 예제에서 decorator_with_args 함수는 데코레이터를 생성하는 함수로서, 실제 데코레이터 함수 decorator는 매개변수 arg를 받습니다.

데코레이터를 작성하면 코드의 재사용성과 모듈화가 증가하며, 기능을 동적으로 확장할 수 있습니다. 함수의 동작을 수정하고 확장하기 위해 데코레이터를 사용하면 유연하고 강력한 코드를 작성할 수 있습니다.