Python:装饰器的原理和案例

电子说

1.2w人已加入

描述

Python中的装饰器用于扩展可调用对象的功能,而无需修改其结构。基本上,装饰器函数包装另一个函数以增强或修改其行为。我们可以通过一个具体的例子了解基础知识!让我们编写一个包含装饰器实现示例的Python3代码:

装饰定义

defdecorator_func_logger(target_func):defwrapper_func():print(“Before calling”, target_func.__name__) target_func() print(“After calling”, target_func.__name__)return wrapper_funcdef target(): print(‘Python is in the decorated target function’)dec_func = decorator_func_logger(target)dec_func()Output:air-MacBook-Air:$ python DecoratorsExample.py(‘Before calling’, ‘target’)Python isin the decorated target function(‘After calling’, ‘target’)

上面的装饰器结构有助于我们在调用目标函数之前和之后在控制台上显示一些注释。

以下是定义装饰器的简单步骤;

首先,我们应该定义一个可调用对象,例如装饰器函数,其中还包含一个包装器函数。

装饰器函数应将目标函数作为参数。

并且它应该返回包装函数,该包装函数扩展了作为参数传递的目标函数。

包装函数应包含目标函数调用以及扩展目标函数行为的代码。

defdecorator_func_logger(target_func):defwrapper_func(): print(“Before calling”, target_func.__name__) target_func() print(“After calling”, target_func.__name__)return wrapper_func@decorator_func_loggerdef target():print(‘Python is in the decorated target function’)target()Output:air-MacBook-Air:$ python DecoratorsExample.py(‘Before calling’, ‘target’)Python isin the decorated target function(‘After calling’, ‘target’)

借助Python提供的语法糖,我们可以简化装饰器的定义,如上所示。

请注意,@ decorator_func_logger仅在我们要装饰的目标函数之前添加。然后,我们可以直接调用目标函数。就像我们在第一个实例中所做的那样,无需显式分配装饰器。

定义多个装饰器并使用参数装饰函数

import timedef decorator_func_logger(target_func):defwrapper_func(*args, **kwargs):print(“Before calling”, target_func.__name__) target_func(*args, **kwargs)print(“After calling”, target_func.__name__)return wrapper_funcdef decorator_func_timeit(target_func):defwrapper_func(*args, **kwargs): ts = time.time() target_func(*args, **kwargs) te = time.time()print (target_func.__name__, (te - ts) * 1000)return wrapper_func@decorator_func_logger@decorator_func_timeitdef target(loop): count = 0 print(‘Python is in the decorated target function’)for number in range(loop): count += numbertarget(100)target(3000)Output:air-MacBook-Air:$ python DecoratorsExample.py(‘Before calling’, ‘wrapper_func’)Python isin the decorated target function(‘target’, 0.015974044799804688)(‘After calling’, ‘wrapper_func’)(‘Before calling’, ‘wrapper_func’)Python isin the decorated target function(‘target’, 0.47397613525390625)(‘After calling’, ‘wrapper_func’)

通过使用‘@’语法在目标函数之前添加多个装饰器,可以轻松地用多个装饰器装饰目标函数。装饰器的执行顺序将与在目标函数之前列出的顺序相同。

请注意,我们的目标函数中有一个参数loop。只要包装函数使用相同的参数,就没有问题。为了确保装饰器可以灵活地接受任意数量的参数,将(* args,** kwargs)参数用于包装函数。

重要要点

装饰器定义可重用的代码块,您可以将这些代码块应用于可调用对象(函数,方法,类,对象),以修改或扩展其行为,而无需修改对象本身。

请考虑您的脚本中有许多函数执行许多不同的任务,并且需要向所有函数添加特定的行为。在这种情况下,将相同的代码块复制到函数中以具有所需的功能不是一个好的解决方案。您可以简单地装饰函数。

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分