【问题标题】:Python 3.x - Data Annotation Validation EquivalentPython 3.x - 数据注释验证等效项
【发布时间】:2013-03-09 12:54:23
【问题描述】:
我正在尝试确定一种方法来实现与 Python 中来自 .NET 的数据注释验证相同的概念。应该是这样的:
class MyClass:
@Property
def Message(self):
return self._message
@Message.setter
@MaxValue(233)
def Message(self, value):
self._message = value
我尝试了不同的方法,但都没有成功。我想访问“值”参数,以便对其应用特定验证。
【问题讨论】:
标签:
python
python-3.x
decorator
assertions
【解决方案1】:
这对你有帮助吗?
这样你就可以用额外的参数来做 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