【发布时间】:2014-01-24 17:55:22
【问题描述】:
我大部分时间都在工作。我想要一个类装饰器(Decorator 类),它接受可用于在对象(Person 的实例)上包装方法的参数(greeting 和 farewell)。
一切正常,除了... Person 类上的原始命令函数永远不会运行!如果我使用类似的方法手动调用函数
output = getattr(instance, func.func_name)(command, *args, **kwargs)
我得到了无限递归。
我该怎么做?完整代码如下:
import functools
class Decorator(object):
def __init__(self, greeting, farewell, *args, **kwargs):
print "initing"
self.greeting = greeting
self.farewell = farewell
def __call__(self, func, *args, **kwargs):
print "CALLING"
@functools.wraps(func)
def wrapper(instance, command, *args, **kwargs):
return "%s, %s! %s!\n%s, %s!" % (
self.greeting,
instance.name,
command,
self.farewell,
instance.name
)
return wrapper
class Person(object):
def __init__(self, name):
self.name = name
@Decorator("Hello", "Goodbye")
def command(self, data):
return data + "LIKE A BOSS"
s = Person("Bob")
print s.command("eat food")
实际输出:
initing
CALLING
Hello, Bob! eat food!
Goodbye, Bob!
预期输出:
initing
CALLING
Hello, Bob! eat food LIKE A BOSS!
Goodbye, Bob!
【问题讨论】:
-
根据您的使用示例,
__call__只需带一个参数:func。