ITPub博客

首页 > IT职业 > IT生活 > 详解python三大器——迭代器、生成器、装饰器

详解python三大器——迭代器、生成器、装饰器

IT生活 作者:专注的阿熊 时间:2021-10-20 17:11:03 0 删除 编辑

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 # 外汇跟单gendan5.com 此处相当 :decorator_1(decorator_2(decorator_get_function_duration(enable=True)(fun)))

@decorator_2 # = 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 it`s duration : 2.002 s

"""


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69946337/viewspace-2838407/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-23

  • 博文量
    248
  • 访问量
    137512