验证python类属性

时间:2018-06-27 09:08:01

标签: python

我想为我的班级属性添加验证。在探索时,我遇到了多个库google appenginedj有自己的属性类来验证属性。由于这是一个常见问题,是否有仅提供基本验证器的python库?

2 个答案:

答案 0 :(得分:0)

可以从方法类中进行python类的验证。有关更多详细信息,请参见python文章中的面向对象编程。

from datetime import datetime
class Person(object):
    def __init__(self, years):
        self.age =  years

    @property
    def age(self):
        return datetime.now().year - self.birthyear

    @age.setter
    def age(self, years):
        if years < 0:
            raise ValueError("Age cannot be negative")
        self.birthyear = datetime.now().year - years

# p = Person(-1)
# ValueError: Age cannot be negative

# p = Person(10)
# p.age = -1
# ValueError: Age cannot be negative

p = Person(19)
print(p.age)       # 19

p.age = p.age + 1
print(p.age)       # 20

p.birthyear = 1992
print(p.age)       # 23

或尝试以下链接: https://smarie.github.io/python-valid8/

答案 1 :(得分:0)

您可以使用pyfields,这很容易将验证添加到类字段中,而与创建构造函数的方式无关(尽管pyfields也提供了轻松创建构造函数的方法)。

例如:

from pyfields import field

class Position:
    x = field(validators=lambda x: x > 0)
    y = field(validators={'y should be between 0 and 100': lambda y: y > 0 and y < 100})

p = Position()
p.x = 1
p.y = 101  # error see below

收益

valid8.entry_points.ValidationError[ValueError]: 
  Error validating [Position.y=101]. InvalidValue: y should be between 0 and 100.
  Function [<lambda>] returned [False] for value 101.

它完全符合mini-lambdavalid8的验证库,因此可以很容易地在字段中添加许多验证器,同时保持代码的可读性:

from pyfields import init_fields
from mini_lambda import x
from valid8.validation_lib import is_in

ALLOWED_COLORS = {'white', 'blue', 'red'}

class Wall:
    height: int = field(validators={'should be a positive number': x > 0,
                                    'should be a multiple of 100': x % 100 == 0},
                        doc="Height of the wall in mm.")
    color: str = field(validators=is_in(ALLOWED_COLORS),
                       default='white',
                       doc="Color of the wall.")

    @init_fields
    def __init__(self, msg):
        print(msg)


w = Wall("hello world!", height=100)
print(vars(w))

有关详细信息,请参见documentation(顺便说一下,我是作者;))