是的,它是语法糖。没有它们,一切都可以实现,但只需多几行代码。但它可以帮助你编写更简洁的代码。
例子:
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
这是一个小样本,仅供玩耍。