问题描述
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())
使用此代码,我们有两个可调用类的实例,一个实例经过修饰,一个实例很简单:
With this code we have two instances of callable class, one is decorated and one is plain:
>>> spud()
Potato @ 140408136280592 called
>>> fancy_spud()
With sour cream and chives! Potato @ 140408134310864 called
我想知道是否支持使用 @对于一个实例,可调用对象上的decorator
语法-与装饰适用于每个实例的类/方法相反。根据,@ syntax只是用于以下目的的糖:
I wonder if it is somehow supported to use the @decorator
syntax on a callable for just one instance - as opposed to decorating the class / method, which would apply to every instance. According to this popular answer, the @syntax is just sugar for:
function = decorator(function)
但这是过度简化?经过我所有的尝试,似乎只有在语法出现在 def
, class
,空白或 @another_decorator
。
But is it an over-simplification? With all my half-baked attempts it seems only to work when the syntax occurs before def
, class
, whitespace or @another_decorator
.
@decorator
baked = Potato()
这是 SyntaxError
。
baked = Potato()
@decorator
baked
也 SyntaxError
。
@decorator
def baked(_spud=Potato()):
return _spud()
有效,但是很丑陋,有点作弊。
Works, but is ugly and kinda cheating.
推荐答案
您提出的问题是:
function = decorator(function)
但是,更准确地说是
@decorator
def function():
pass
是语法糖用于:
def function():
pass
function = decorator(function)
装饰器专门用于装饰函数,方法或类 definitions 。引入了类修饰符的描述了语法:
Decorators are designed to decorate function, method or class definitions, specifically. The PEP that introduced class decorators describes the grammar:
decorated: decorators (classdef | funcdef)
funcdef: 'def' NAME parameters ['->' test] ':' suite
如您所见,装饰器必须紧接 classdef
或 funcdef
,因此无法直接在可调用类的实例上使用它。
As you can see, a decorator must come immediately before a classdef
or funcdef
, so there is no way to use it directly on an instance of a callable class.
这篇关于如何装饰可调用类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!