fromfunctoolsimportwrapsimporttimedeftimer(func):
@wraps(func)
defwrapper(*args, **kwargs):
start=time.perf_counter()
#Calltheactualfunctionres=func(*args, **kwargs)
duration=time.perf_counter() -startprint(f'[{wrapper.__name__}] took {duration * 1000} ms')
returnresreturnwrapper@timerdefisprime(number: int):
""" Checks whether a number is a prime number """isprime=Falseforiinrange(2, number):
if ((number%i) ==0):
isprime=Truebreakreturnisprimeif__name__=="__main__":
isprime(number=155153)
defprompt_sure(prompt_text:str):
""" Shows prompt asking you whether you want to continue. Exits on anything but y(es) """defouter_wrapper(func):
defwrapper(*args, **kwargs):
if (input(prompt_text).lower() !='y'):
returnreturnfunc(*args, **kwargs)
returnwrapperreturnouter_wrapper我们依然使用sayhello函数来演示该装饰器的功能defprompt_sure(prompt_text:str):
""" Shows prompt asking you whether you want to continue. Exits on anything but y(es) """defouter_wrapper(func):
defwrapper(*args, **kwargs):
if (input(prompt_text).lower() !='y'):
returnreturnfunc(*args, **kwargs)
returnwrapperreturnouter_wrapper@prompt_sure('Sure? Press y to continue, press n to stop. ')
defsayhello():
print("hi")
if__name__=="__main__":
sayhello()
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
我们能够在装饰器上设置提示消息。当我们调用sayhello()时,会看到Sure? Press y to continue, press n to stop.如果输入 'y' 那么我们将执行sayhello(),任何其他输入(包括没有输入将阻止sayhello()执行)。
deftrycatch(func):
""" Wraps the decorated function in a try-catch. If function fails print out the exception. """@wraps(func)
defwrapper(*args, **kwargs):
try:
res=func(*args, **kwargs)
returnresexceptExceptionase:
print(f"Exception in {func.__name__}: {e}")
returnwrapper我们将在下面的函数中使用这个装饰器deftrycatch(func):
""" Wraps the decorated function in a try-catch. If function fails print out the exception. """@wraps(func)
defwrapper(*args, **kwargs):
try:
res=func(*args, **kwargs)
returnresexceptExceptionase:
print(f"Exception in {func.__name__}: {e}")
returnwrapper@trycatchdeftrycatchExample(numA:float, numB:float):
returnnumA/numBif__name__=="__main__":
trycatchExample(9.3)
trycatchExample(9,0)
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
现在,当我们调用trycatchExample(9, 3)函数时返回3.0。如果我们调用trycatchExample(9, 0)(除以 0),它会正确返回以下内容Exception in trycatchExample: division by zero