我正在学习 Python 中的装饰器,并希望使用它们来修改代码中几个更复杂函数的行为。具体来说,我想:
这是我的一个函数的示例,它处理数字列表,过滤掉偶数,并计算剩余奇数的总和:
def my_function(numbers):
odd_numbers = [n for n in numbers if n % 2 != 0]
result = sum(odd_numbers)
return result
我还有另一个函数,通过反转句子中的单词来处理字符串:
def reverse_sentence(sentence):
words = sentence.split()
reversed_sentence = ' '.join(reversed(words))
return reversed_sentence
我了解如何创建一个简单的装饰器,但是如何创建一个具有以下功能的装饰器:
我想将此装饰器应用于这两个函数(以及可能的其他函数)。任何有关示例的帮助将不胜感激!
也许这个例子会有所帮助:
import time
def measure_function(f):
def execute(*args, **kwargs):
t = time.time()
try:
res = f(*args, **kwargs)
print("function %s cost %s seconds" % (f, time.time()-t))
return res
except Exception as error:
print("function %s failed with error: %s" % (f, error))
return execute
@measure_function
def my_function(numbers):
odd_numbers = [n for n in numbers if n % 2 != 0]
result = sum(odd_numbers)
return result
print(my_function([1,2,3,5,6,7,8]))
@measure_function
def reverse_sentence(sentence):
words = sentence.split()
reversed_sentence = ' '.join(reversed(words))
return reversed_sentence
print(reverse_sentence("Logs the execution time of each function"))