gpt4 book ai didi

成员函数的 Python @precondition/@postcondition - 怎么样?

转载 作者:太空狗 更新时间:2023-10-29 22:13:49 25 4
gpt4 key购买 nike

我正在尝试对类的成员函数返回的值使用@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 .

我假设出现错误是因为@postcondition 的基础函数不期望处理成员函数(当然我见过的所有示例都只是使用普通的旧函数)但我不确定如何修复它让我可以做到这一点?

如有任何建议,我们将不胜感激。

最佳答案

你不需要做任何特别的事情:

import functools

def condition(pre_condition=None, post_condition=None):
def decorator(func):
@functools.wraps(func) # presever name, docstring, etc
def wrapper(*args, **kwargs): #NOTE: no self
if pre_condition is not None:
assert pre_condition(*args, **kwargs)
retval = func(*args, **kwargs) # call original function or method
if post_condition is not None:
assert post_condition(retval)
return retval
return wrapper
return decorator

def pre_condition(check):
return condition(pre_condition=check)

def post_condition(check):
return condition(post_condition=check)

用法:

@pre_condition(lambda arg: arg > 0)
def function(arg): # ordinary function
pass

class C(object):
@post_condition(lambda ret: ret > 0)
def method_fail(self):
return 0
@post_condition(lambda ret: ret > 0)
def method_success(self):
return 1

测试:

function(1)
try: function(0)
except AssertionError: pass
else: assert 0, "never happens"

c = C()
c.method_success()
try: c.method_fail()
except AssertionError: pass
else: assert 0, "never happens"

关于成员函数的 Python @precondition/@postcondition - 怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12151182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com