cor*_*ump 15 python decorator syntactic-sugar
可能重复:
了解Python装饰器
我很擅长使用Python装饰器,而且据我所知,我的第一印象是它们只是语法糖.
是否有更深刻的用途用于更复杂的用途?
ran*_*lan 14
是的,它是语法糖.没有它们,一切都可以实现,但需要更多代码.但它可以帮助您编写更简洁的代码.
例子:
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
这是一个小样本.