def decorator(fn):
def wrapper(*args, **kwargs):
print 'With sour cream and chives!',
return fn(*args, **kwargs)
return wrapper
class Potato(object):
def __call__(self):
print 'Potato @ {} called'.format(id(self))
spud = Potato()
fancy_spud = decorator(Potato())
通过这段代码,我们有两个可调用类的实例,一个是修饰的,一个是普通的:
>>> spud()
Potato @ 140408136280592 called
>>> fancy_spud()
With sour cream and chives! Potato @ 140408134310864 called
我想知道是否以某种方式支持使用@decorator
仅针对一个实例的可调用语法 - 与装饰类/方法相反,后者适用于每个实例。根据this https://stackoverflow.com/a/1594484/674039流行的答案是,@syntax 只是糖:
function = decorator(function)
但这是否过于简单化了?在我所有不成熟的尝试中,它似乎只有在语法出现之前才有效def
, class
、空格或@another_decorator
.
@decorator
baked = Potato()
那是一个SyntaxError
.
baked = Potato()
@decorator
baked
Also SyntaxError
.
@decorator
def baked(_spud=Potato()):
return _spud()
有效,但很丑而且有点作弊。