2012-09-06 25 views
9

可能重复:
Understanding Python decoratorsPython装饰只是语法糖?

我很新的使用Python装饰,从我对我的第一印象明白,他们只是语法糖。

更复杂的用途是否有更深刻的用途?

+2

这里有一个全面的答案与使用示例在这里http://stackoverflow.com/questions/739654/understanding-python-decorators#answer-1594484 –

+0

谢谢。这真的很有用,我不知道如何关闭或删除这篇文章。如果有人能做到这一点,那就太好了。 – coredump

+0

这里是一个小教程,所以你可以看到他们是什么:https://www.codementor.io/python/tutorial/introduction-to-decorators – Sheena

回答

10

是的,它是语法糖。一切都可以在没有它们的情况下实现,但需要更多的代码。但它可以帮助您编写更简洁的代码。

实例:

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 

这是一个小样本只是一起玩。