乐趣区

关于python:详解python三大器迭代器生成器装饰器

def decorator_get_function_duration(enable):

"""
:param enable:  是否须要统计函数执行耗时
:return: 
"""print("this is decorator_get_function_duration")
def inner(func):
    print('this is inner in decorator_get_function_duration')
    @wraps(func)
    def wrapper(*args, **kwargs):
        print('this is a wrapper in decorator_get_function_duration.inner')
        if enable:
            start = time.time()
            print(f"函数执行前:{start}")
            result = func(*args, **kwargs)
            print('[%s]`s enable was %s it`s duration : %.3f s' % (func.__name__, enable, time.time() - start))
        else:
            result = func(*args, **kwargs)
        return result
    return wrapper
return inner

def decorator_1(func):

print('this is decorator_1')
@wraps(func)
def wrapper(*args, **kwargs):
    print('this is a wrapper in decorator_1')
    return func(*args, **kwargs)
return wrapper

def decorator_2(func):

print('this is decorator_2')
@wraps(func)
def wrapper(*args, **kwargs):
    print('this is a wrapper in decorator_2')
    return func(*args, **kwargs)
return wrapper

@decorator_1 # 此处相当:decorator_1(decorator_2(decorator_get_function_duration(enable=True)(fun)))
@decorator_2 # = PayPal 下载 decorator_2(decorator_get_function_duration(enable=True)(fun))
@decorator_get_function_duration(enable=True) # = decorator_get_function_duration(enable=True)(fun)
def fun():

time.sleep(2)
print("fun 执行完了~")

fun()

======== enable=False ============

“””
this is decorator_get_function_duration
this is inner in decorator_get_function_duration
this is decorator_2
this is decorator_1
this is a wrapper in decorator_1
this is a wrapper in decorator_2
this is a wrapper in decorator_get_function_duration.inner
fun 执行完了~
“””

======== enable=True ============

“””
this is decorator_get_function_duration
this is inner in decorator_get_function_duration
this is decorator_2
this is decorator_1
this is a wrapper in decorator_1
this is a wrapper in decorator_2
this is a wrapper in decorator_get_function_duration.inner
函数执行前:1634635708.648994
fun 执行完了~
[fun]s enable was True its duration : 2.002 s
“””

退出移动版