Python装饰只是语法糖?
  可能重复: 
  了解Python装饰器 
我在使用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
这只是一个小样本而已。
我非常喜欢装饰器语法,因为它使代码更加清晰
例如,在Django中有这个login_required装饰器:https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required
要为函数/视图注入@login_required行为,你所要做的就是将修饰器附加到它(而不是把if:... else:...控制表达式等处处)。
阅读PEP!
http://www.python.org/dev/peps/pep-0318/
它在所作出的语言决策上有失败的历史,以及为什么
链接地址: http://www.djcxy.com/p/23795.html