본문 바로가기

Language/Python

python closure, decorator

Closure


ex 1 )

# python 3.x

def MyFunction(text):
	def innerFunction():
        return print("receive string is {}".format(text))
    return innerFunction

test_Function = MyFunction("Hello World!")
test_Function()


ex 2 )

# python 3.x

def MyFunction(originFunction):
    def innerFunction():
        print (" This is innerFunction ")
        return originFunction()
    return innerFunction

def doSomething():
    print ("Hello World!")
    
test_Function = MyFunction(doSomething)
test_Function()



Decorator


함수 사용.

  • 단일 인자인경우

# python 3.x

def MyFunction(originFunction):
    def innerFunction():
        print (" This is innerFunction ")
        return originFunction()
    return innerFunction

@MyFunction
def doSomething():
    print ("Hello World!")
    
doSomething()


  • 복수 인자인경우

# python 3.x

def MyFunction(originFunction):
    def innerFunction(*args, **kwargs):
        print (" This is innerFunction ")
        return originFunction(*args, **kwargs)
    return innerFunction

@MyFunction
def doSomething(name, age):
    print ("Name = {}, age = {}".format(name, age))
    
doSomething("Kangprog", "0")


클래스 사용.

  • 단일 인자인경우

# python 3.x

class MyDecoratorClass:
    def __init__(self, originFunction):
        self.originFunction = originFunction
       
    def __call__(self):
        print ("This is innerFunction")
        return self.originFunction()

@MyDecoratorClass
def doSomething():
    print ("Hello World!")
 
doSomething()


  • 복수 인자인경우

# python 3.x

class MyDecoratorClass:
    def __init__(self, originFunction):
        self.originFunction = originFunction
       
    def __call__(self, *args, **kwargs):
        print ("This is innerFunction")
        return self.originFunction(*args, **kwargs)

@MyDecoratorClass
def doSomething(name, age):
    print ("Name = {}, age = {}".format(name, age))
 
doSomething("kangprog", "0")

 

 

반응형

'Language > Python' 카테고리의 다른 글

Selenium 간단 정리  (0) 2019.07.17
파이썬 multiprocessing 모듈 (map_async, apply_async)  (0) 2019.07.16
python logging 예제  (0) 2019.01.26
python chrome password  (0) 2019.01.13
python pysqlite  (0) 2019.01.05