[Python] Closure and Decorator

SYieeยท2022๋…„ 10์›” 17์ผ
0

๊ฒŒ์ž„ํ”„๋กœ๊ทธ๋ž˜๋ฐ

๋ชฉ๋ก ๋ณด๊ธฐ
5/6
post-thumbnail

Closure

๐Ÿ“Œ Function that remembers values in enclosing scope.

def print2(msg):
    def printer():
          print(msg)
    return printer
  • add_number ํ•จ์ˆ˜์˜ return ๊ฐ’์ด ํ•จ์ˆ˜ adder์ด๋‹ค.
  • adder์— ์‚ฌ์šฉ๋˜๋Š” num ๋ณ€์ˆ˜๋Š” local variable์ด ์•„๋‹ˆ๋ฉฐ add_number ํ•จ์ˆ˜์—์„œ parameter๋กœ ์‚ฌ์šฉ๋œ ๊ฐ’์œผ๋กœ ์“ฐ์ธ๋‹ค
def add_number(num):
    def adder(number):
      print('adder is a closure')
      return num + number
  return adder
  
a_10 = add_number(10) #num = 10
a_20 = add_number(20) #num = 20

a1 = a_10(21) # prints 'adder is โ€ฆ'
a2 = a_20(21) # prints 'adder is โ€ฆ'
print(a1) #31
print(a2) #41

more information

Decorator

๐Ÿ“Œ Callable object that is used to modify a function or a class

โœ… Function Decorator

def NewDecorator(func):
    #@wraps(func) # ํ•จ์ˆ˜๋ช… ๋ฐ ์„ค๋ช…๋ฌธ ์œ ์ง€, ์—†์œผ๋ฉด(NewAdd)
    def NewAdd(*args, **kwargs): #์ผ๋ฐ˜ํ™”๋œ function arguments
        print('Before call')
        result = func(*args, **kwargs)
        print('After call')
        return result
    return NewAdd


@NewDecorator #add ํ•จ์ˆ˜ callํ•  ๋•Œ NewDecoratorํ•จ์ˆ˜๋„ ํ˜ธ์ถœ
def add(a, b): 
    print('Add')
    return a + b
sum = add(1, 3) # โ€˜Before callโ€™ โ€˜Addโ€™ โ€˜After callโ€™ 4
#print(sum)
#print(add.__name__)

โœ… Class Decorator

โœ… Built-in Decorator

setter, getter, deleter

profile
๊ฒŒ์ž„ ๊ฐœ๋ฐœ์ž

0๊ฐœ์˜ ๋Œ“๊ธ€