我有一个装饰器声明为一个类:
class predicated(object):
def __init__(self,fn):
self.fn = fn
self.fpred = lambda *args,**kwargs: True
def predicate(self,predicate):
self.fpred = predicate
return self
def validate(self,*args,**kwargs):
return self.fpred(*args,**kwargs)
def __call__(self,**kwargs):
if not self.validate(*args,**kwargs):
raise PredicateNotMatchedError("predicate was not matched")
return self.fn(*args,**kwargs)
…当我用它来包装类中的方法时,调用该方法似乎并没有将对象的实例设置为第一个参数.虽然这种行为并不完全出乎意料,但当方法成为实例方法时,如何让自我被冻结?
简化示例:
class test_decorator(object):
def __init__(self,fn):
self.fn = fn
def __call__(self,**kwargs):
return self.fn(*args,**kwargs)
class Foo(object):
@test_decorator
def some_method(self):
print(self)
Foo().some_method()
foo的预期实例,而是得到一个错误,说0参数被传递.
最佳答案