Python decorators just syntactic sugar?(巨蟒装饰器只是句法上的糖吗?)
本文介绍了巨蟒装饰器只是句法上的糖吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复项:
Understanding Python decorators
我对使用Python修饰符还很陌生,根据我的第一印象,它们只是语法上的糖。
有没有更深入的用法用于更复杂的用途?
推荐答案
是的,它是句法上的糖。没有它们,一切都可以实现,但只需多几行代码。但它可以帮助您编写更简洁的代码。
示例:
from functools import wraps
def requires_foo(func):
@wraps(func)
def wrapped(self, *args, **kwargs):
if not hasattr(self, 'foo') or not self.foo is True:
raise Exception('You must have foo and be True!!')
return func(self, *args, **kwargs)
return wrapped
def requires_bar(func):
@wraps(func)
def wrapped(self, *args, **kwargs):
if not hasattr(self, 'bar') or not self.bar is True:
raise Exception('You must have bar and be True!!')
return func(self, *args, **kwargs)
return wrapped
class FooBar(object):
@requires_foo # Make sure the requirement is met.
def do_something_to_foo(self):
pass
我们还可以将装饰物链接/堆叠在一起。
class FooBar(object):
@requires_bar
@requires_foo # You can chain as many decorators as you want
def do_something_to_foo_and_bar(self):
pass
好的,我们最终可能会有很多很多的装饰物叠加在一起。
我知道!我将编写一个应用其他装饰器的装饰器。
所以我们可以这样做:
def enforce(requirements):
def wrapper(func):
@wraps(func)
def wrapped(self, *args, **kwargs):
return func(self, *args, **kwargs)
while requirements:
func = requirements.pop()(func)
return wrapped
return wrapper
class FooBar(object):
@enforce([reguires_foo, requires_bar])
def do_something_to_foo_and_bar(self):
pass
这是一个仅供玩耍的小样本。
这篇关于巨蟒装饰器只是句法上的糖吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:巨蟒装饰器只是句法上的糖吗?


基础教程推荐
猜你喜欢
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01