我试图在类的成员函数返回的值上使用 @postcondition 装饰器,如下所示:
def out_gt0(retval, inval):
assert retval > 0, "Return value < 0"
class foo(object):
def __init__(self, w, h):
self.width = w
self.height = h
@postcondition(out_gt0)
def bar(self):
return -1
当我尝试调用成员函数“bar”(并因此引发@postcondition提供警告)时,我得到以下信息:
>>> f = foo(2,3)
>>> f.bar()
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
f.bar()
File "<pyshell#8>", line 106, in __call__
result = self._func(*args, **kwargs)
TypeError: bar() takes exactly 1 argument (0 given)
>>>
我对 @postcondition 的定义是这里看到的http://wiki.python.org/moin/PythonDecoratorLibrary#Pre-.2FPost-Conditions http://wiki.python.org/moin/PythonDecoratorLibrary#Pre-.2FPost-Conditions.
我假设出现错误是因为 @postcondition 底层的函数不希望处理成员函数(当然我见过的所有示例都只是使用普通的旧函数),但我不确定如何修复它,所以我可以这样做吗?
如有任何建议,将不胜感激。