Python 装饰师的真正用途是什么? 我试图了解装饰师在现实世界中的使用。
作为装饰师,我们都知道它是用来装饰功能的。 这意味着我们可以在现有函数中添加一些额外的内容,但也可以通过使用其他简单函数来完成。我们也可以调用一个函数来调用另一个函数。那么为什么我们需要使用装饰器呢 我已经试过制作两个程序Python 装饰师的真正用途是什么? 我试图了解装饰师在现实世界中的使用。,python,python-3.x,python-3.7,python-decorators,Python,Python 3.x,Python 3.7,Python Decorators,作为装饰师,我们都知道它是用来装饰功能的。 这意味着我们可以在现有函数中添加一些额外的内容,但也可以通过使用其他简单函数来完成。我们也可以调用一个函数来调用另一个函数。那么为什么我们需要使用装饰器呢 我已经试过制作两个程序 与装饰师一起 def decor_result(result_as_argument): def new_function(marks): for i in marks: if i>= 75: prin
def decor_result(result_as_argument):
def new_function(marks):
for i in marks:
if i>= 75:
print("Congrats distiction",i)
else:
result_as_argument(marks)
return new_function
@decor_result
def result(marks):
for i in marks:
if i >= 35:
pass
else:
print("Fail")
break
else:
print("Pass")
result([79,65,55,78,12])
def result_distict(marks):
for i in marks:
if i>= 75:
print("Congrats distiction",i)
else:
result(marks)
def result(marks):
for i in marks:
if i >= 35:
pass
else:
print("Fail")
break
else:
print("Pass")
result_distict([79,65,55,78,12])
result([79,65,55,78,12])
def decor_result(result_as_argument):
def new_function(marks):
for i in marks:
if i>= 75:
print("Congrats distiction",i)
else:
result_as_argument(marks)
return new_function
@decor_result
def result(marks):
for i in marks:
if i >= 35:
pass
else:
print("Fail")
break
else:
print("Pass")
result([79,65,55,78,12])
def result_distict(marks):
for i in marks:
if i>= 75:
print("Congrats distiction",i)
else:
result(marks)
def result(marks):
for i in marks:
if i >= 35:
pass
else:
print("Fail")
break
else:
print("Pass")
result_distict([79,65,55,78,12])
result([79,65,55,78,12])
通过这样做,我了解到,如果不使用decorator,它会更加简化,我们可以自由地使用我们想要的任何函数,而通过使用decorator,我们不能使用旧函数,那么为什么以及在哪里使用decorator?在您的示例中,不需要使用decorator。当您试图实现一组函数的特定行为时,您希望使用装饰器。例如,假设您试图显示脚本中所有函数的执行时间 解决方案1)您可以在任何地方添加一段代码来显示它:
from time import time
def f1():
t0 = time()
# f1 body
print("Execution time of f1: {}".format(time()-t0))
def f2():
t0 = time()
# f2 body
print("Execution time of f2: {}".format(time()-t0))
正如您所看到的,代码非常重复。如果要更改此共享行为中的任何内容,则必须修改所有函数。这就是装饰师有用的地方
2) 使用装饰器:
def timer(func):
def wrapper(*args,**kwargs):
t0 = time()
res = func(*args,**kwargs)
duration = time()-t0
print("Execution time of {}: {} s".format(func.__name__, duration))
return res
return wrapper
@timer
def f1():
# body of f1
@timer
def f2():
# body of f2
.延伸,只是一点点;这是关于模式的。当您想要对多个函数进行相同的扩展时,装饰器只编写一次,然后反复应用,而更简单的方法要求每个函数都使用相同的代码包装,也就是说,您需要重复自己。