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
这是一个仅供玩耍的小样本。
这篇关于巨蟒装饰器只是句法上的糖吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:巨蟒装饰器只是句法上的糖吗?
基础教程推荐
猜你喜欢
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
