๐Ÿ Python & library/Python

Python decorator @

๋ณต๋งŒ 2021. 8. 4. 23:38

Python ์—๋Š” ํ•จ์ˆ˜๋ฅผ ๊พธ๋ฉฐ์ค„ ์ˆ˜ ์žˆ๋Š” decorator๋ผ๋Š” ๊ธฐ๋Šฅ์ด ์กด์žฌํ•œ๋‹ค.

Decorator์€ @ ๊ธฐํ˜ธ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ, ํ•จ์ˆ˜์˜ ์•ž๊ณผ ๋’ค์— ์ถ”๊ฐ€์ ์ธ ๋‚ด์šฉ์„ ๋”ํ•ด์ค€๋‹ค.

 

์ฒ˜์Œ์— ๋ดค์„ ๋• @๊ฐ€ ๋ญ”๊ฐ€ ์‹ถ์–ด์„œ Python @๋ผ๊ณ  ๊ฒ€์ƒ‰ํ–ˆ๋”๋‹ˆ ๊ฒ€์ƒ‰๊ฒฐ๊ณผ๊ฐ€ ์•ˆ๋‚˜์™€์„œ ๋‹นํ™ฉํ–ˆ๋‹ค..

 

1) nested function์˜ ํ˜•ํƒœ์™€, 2) decorator class ๋‘ ๊ฐ€์ง€ ํ˜•ํƒœ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

1) nested function

- decorator ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•ด์ค€๋‹ค (test_decorator).

- decorator ํ•จ์ˆ˜๋Š” input์œผ๋กœ ํ•จ์ˆ˜๋ฅผ ๋ฐ›๊ณ , ์•ž๋’ค๋กœ ์ทจํ•ด์ค„ action์„ ์ •์˜ํ•œ ํ›„ ํ•ด๋‹น ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ด ์ฃผ๋ฉด ๋œ๋‹ค.

- decorator์„ ์‚ฌ์šฉํ•  ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•˜๊ธฐ ์ „ decorator ๊ธฐํ˜ธ @์™€ ํ•จ๊ป˜ decorator ํ•จ์ˆ˜์˜ ์ด๋ฆ„์„ ์ ์–ด ์ฃผ๋ฉด ๋œ๋‹ค.

def test_decorator(func):
    def wrapper(*args, **kwargs):
        print('---function starts---')
        func(*args, **kwargs)
        print('---function ends---')
    return wrapper

@test_decorator
def example_f(input_str):
	print(input_str)

example_f('hello')
>> ---function starts---
hello
---function ends---

 

2) decorator class

- decorator class๋ฅผ ์ •์˜ํ•ด์ค€๋‹ค (Test_decorator).

__init__()์—์„œ input์œผ๋กœ ํ•จ์ˆ˜๋ฅผ ๋ฐ›๊ณ ,

__call__()์—์„œ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์ทจํ•ด์ค„ action์„ ์ •์˜ํ•œ ํ›„ ํ•ด๋‹น ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ด ์ฃผ๋ฉด ๋œ๋‹ค.

- ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ decorator์„ ์‚ฌ์šฉํ•  ํ•จ์ˆ˜ ์œ„์— @ ๊ธฐํ˜ธ์™€ ํ•จ๊ป˜ decorator class ์ด๋ฆ„์„ ์ ์–ด ์ฃผ๋ฉด ๊ฐ™์€ ์ž‘์šฉ์„ ํ•œ๋‹ค.

class Test_decorator:
    def __init__(self, func):
        self.func = func
    def __call__(self, *args, **kwargs):
        print('---function starts---')
        func(*args, **kwargs)
        print('---function ends---')

@Test_decorator
def example_f(input_str):
    print(input_str)

example_f('hello')
>> ---function starts---
hello
---function ends---
๋ฐ˜์‘ํ˜•