STUDY/Python

참고 | 고차함수 호출 | decorators | wrap

nicesugi 2022. 5. 20. 01:37
import datetime

def datetime_decorator(func):
        def decorated():
                print datetime.datetime.now()
                func()
                print datetime.datetime.now()
        return decorated

@datetime_decorator
def main_function_1():
        print "MAIN FUNCTION 1 START"

@datetime_decorator
def main_function_2():
        print "MAIN FUNCTION 2 START"

@datetime_decorator
def main_function_3():
        print "MAIN FUNCTION 3 START"
        
..... X 100번



출처: https://bluese05.tistory.com/30
import datetime

class DatetimeDecorator:
        def __init__(self, f):
                self.func = f

        def __call__(self, *args, **kwargs):
                print datetime.datetime.now()
                self.func(*args, **kwargs)
                print datetime.datetime.now()

class MainClass:
        @DatetimeDecorator
        def main_function_1():
                print "MAIN FUNCTION 1 START"

        @DatetimeDecorator
        def main_function_2():
                print "MAIN FUNCTION 2 START"

        @DatetimeDecorator
        def main_function_3():
                print "MAIN FUNCTION 3 START"

my = MainClass()
my.main_function_1()
my.main_function_2()
my.main_function_3()



출처: https://bluese05.tistory.com/30
def a_decorator(func):
    def wrapper(*args, **kwargs):
        """A wrapper function"""
        # Extend some capabilities of func
        func()
    return wrapper
 
@a_decorator
def first_function():
    """This is docstring for first function"""
    print("first function")
 
@a_decorator
def second_function(a):
    """This is docstring for second function"""
    print("second function")
 
print(first_function.__name__)
print(first_function.__doc__)
print(second_function.__name__)
print(second_function.__doc__)


# output:
wrapper
A wrapper function
wrapper
A wrapper function


print("First Function")
help(first_function)
 
print("\nSecond Function")
help(second_function)


# output:
First Function
Help on function wrapper in module __main__:

wrapper(*args, **kwargs)
    A wrapper function


Second Function
Help on function wrapper in module __main__:

wrapper(*args, **kwargs)
    A wrapper function




출처:https://www.geeksforgeeks.org/python-functools-wraps-function/

 

 

 

-Demystifying @decorators in Python

https://sumit-ghosh.com/articles/demystifying-decorators-python/

 

Demystifying @decorators in Python

Introduction

sumit-ghosh.com

 

 

 

고차 함수 호출 

https://docs.python.org/2/library/functools.html#functools.wraps

 

9.8. functools — Higher-order functions and operations on callable objects — Python 2.7.18 documentation

 

docs.python.org

 

반응형