【发布时间】:2014-07-30 02:54:32
【问题描述】:
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 流行的回答,@syntax 只是糖:
function = decorator(function)
但这是否过于简单化了?在我所有半生不熟的尝试中,它似乎只有在语法出现在def、class、空格或@another_decorator之前才有效。
@decorator
baked = Potato()
那是SyntaxError。
baked = Potato()
@decorator
baked
还有SyntaxError。
@decorator
def baked(_spud=Potato()):
return _spud()
有效,但丑陋且有点作弊。
【问题讨论】: