我大部分时间都在工作。我希望有一个类装饰器(Decorator
类)接受可用于在对象上包装方法的参数(greeting
和farewell
)({{1}的实例})。
一切正常,但...... Person
类的原始命令功能永远不会运行!如果我使用
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!
答案 0 :(得分:4)
您从未致电func
以获取原始讯息:
def wrapper(instance, command, *args, **kwargs):
original_value = func(instance, command) #call func here
return "%s, %s! %s!\n%s, %s!" % (
self.greeting,
instance.name,
original_value,
self.farewell,
instance.name
)
<强>输出:强>
initing
CALLING
Hello, Bob! eat food LIKE A BOSS!
Goodbye, Bob!
答案 1 :(得分:0)
您必须在包装器中的某处调用func(data)以获取“LIKE A BOSS”结果并将其添加到预期输出