相关疑难解决方法(0)

如何装饰可调用类的实例?

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())
Run Code Online (Sandbox Code Playgroud)

使用此代码,我们有两个可调用类的实例,一个是装饰的,一个是普通的:

>>> spud()
Potato @ 140408136280592 called
>>> fancy_spud()
With sour cream and chives! Potato @ 140408134310864 called
Run Code Online (Sandbox Code Playgroud)

我想知道是否支持@decorator在一个实例上使用可调用的语法 - 而不是装饰适用于每个实例的类/方法.根据这个流行的答案,@syntax只是糖:

function = decorator(function)
Run Code Online (Sandbox Code Playgroud)

但这是一种过度简化吗?用我所有的半吊子尝试,似乎只有当语法发生前的工作def,class,空格或@another_decorator.

@decorator
baked = Potato()
Run Code Online (Sandbox Code Playgroud)

那是一个SyntaxError.

baked = Potato()
@decorator
baked
Run Code Online (Sandbox Code Playgroud)

还有SyntaxError …

python decorator

6
推荐指数
2
解决办法
311
查看次数

标签 统计

decorator ×1

python ×1