[Python] 데코레이터 심화

2022. 11. 29. 17:23

지난글(https://sso-y.tistory.com/15)에 이어 데코레이터 심화를 보자.

 

[Python] First-class 함수, Closure 함수, 데코레이터 (Decorator)

decorator를 알기 전 First-class 함수와 Closure 함수를 알아야 한다. 우선 제일 중요한 것은 파이썬에는 함수는 객체다 라는 것이다. First-class function 코드부터 보자 def info(name): return 'Hi ' + name info함수

sso-y.tistory.com

 

데코레이터 여러개

데코레이터 두개를 받아보자.

def aster(function):
    def inner_func(*args, **kwargs):
        return '*' + function(*args, **kwargs) + '*'
    return inner_func

def hash(function):
    def inner_func(*args, **kwargs):
        return '#' + function(*args, **kwargs) + '#'
    return inner_func

@aster
@hash
def sentence(s):
    return s

print(sentence('Hello World'))

 

 

*#Hello World#*

 

실행 순서는 먼저 선언한 데코레이터부터다.

  1. @aster
    1. @hash ~ def sentence를 function으로 봄
    2. * 출력 후@hash ~ def sentence 실행
  2. @hash
    1. def sentecne를 function으로 봄
    2. # 출력 후 sentence(s)실행 
    3. # 출력 후 return
  3. * 출력 후 return

 

데코레이터에 파라미터 추가

 

데코레이터에 파라미터를 추가해보자.

 

def decorator_param(param):
    def outer_func(function):
        def inner_func(*args, **kwargs):
            print('받은 param : {}'.format(param))
            return function(*args, **kwargs)
        return inner_func
    return outer_func

이 경우 함수가 하나 더 추가 된다!

 

사용해보자.

@decorator_param(123)
def recieve():
    print('recieved')

recieve()

받은 param : 123
recieved

 

 

 


class ExampleClass:
    @classmethod
    def example_method(cls, **kwargs):
        # 입력 검증
        assert "name" in kwargs, "Check your name"
        assert "age" in kwargs, "Check your age"

        # 내부 함수 정의
        def greet_person(name, age):
            return f"Hello, {name}! You are {age} years old."

        # 주요 작업
        name = kwargs["name"]
        age = kwargs["age"]
        greeting = greet_person(name, age)

        return greeting

result = ExampleClass.example_method(name="Alice", age=30)
print(result)  # 출력: Hello, Alice! You are 30 years old.