Python 装饰器

Python Decorator

Posted by BlueFat on Saturday, August 20, 2022

无参装饰器

import datetime
import time
import functools

def logger(fn):
    @functools.wraps(fn) #wrap解决文档、名称问题
    def wrapper(*args,**kwargs):
        """+++Wrapper Function+++"""
        start=datetime.datetime.now()
        ret = fn(*args,**kwargs) #add
        delta=(datetime.datetime.now()-start).total_seconds()
        print(fn.__name__,delta)
        return ret
    return wrapper

@logger  # add=logger(add) === add=wrapper
def add(x,y):
    """Add Function"""
    time.sleep(1)
    return x+y
    
print(add(4,5))
print(add.__name__,add.__doc__)
add 1.004984
9
add Add Function

带参装饰器