巨蟒装饰器只是句法上的糖吗? [英] Python decorators just syntactic sugar?

查看:19
本文介绍了巨蟒装饰器只是句法上的糖吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
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

这是一个仅供玩耍的小样本。

这篇关于巨蟒装饰器只是句法上的糖吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆