python 修饰器 参数_具有参数的Python类修饰器,但未运行修饰的...
我已經(jīng)大部分工作了.我想要一個類裝飾器(Decorator類),該裝飾器接受可用于將方法包裝在對象(Person的實例)上的參數(shù)(問候和告別).
一切正常,除了…永遠不會運行Person類上的原始命令功能!如果我使用類似的方法手動調(diào)用該函數(shù)
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!
%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!
預期產(chǎn)量:
initing
CALLING
Hello, Bob! eat food LIKE A BOSS!
Goodbye, Bob!
總結
以上是生活随笔為你收集整理的python 修饰器 参数_具有参数的Python类修饰器,但未运行修饰的...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 反射 json_java 反射
- 下一篇: 【LeetCode笔记】121. 买卖股