Python 3.x - 数据注解验证等效
我正在寻找一种方法,把.NET中的数据注解验证的概念在Python中实现。大概是这样的:
class MyClass:
@Property
def Message(self):
return self._message
@Message.setter
@MaxValue(233)
def Message(self, value):
self._message = value
我尝试了不同的方法,但都没有成功。我想要访问“value”这个参数,以便对它进行特定的验证。
1 个回答
2
这对你有帮助吗?
这样你就可以在Python中添加带有额外参数的注释了。
def MaxValue(maxValue):
def wrapFunction(function):
def replacedMaxValueFunction(self, value):
assert value <= maxValue
return function(self, value)
replacedMaxValueFunction.__name__ = function.__name__
return replacedMaxValueFunction
return wrapFunction
所以现在你可以这样做:我不确定这是否符合C#的标准,但希望它能进行你想要的检查。
>>> @MaxValue(123)
def f(self, value):
print(value)
>>> f(1, 123)
123
>>> f(1, 124)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
f(1, 124)
File "<pyshell#1>", line 4, in replacedMaxValueFunction
assert value <= maxValue
AssertionError