詳解python三大器——迭代器、生成器、裝飾器

專注的阿熊發表於2021-10-20

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/,如需轉載,請註明出處,否則將追究法律責任。

相關文章