在python中验证数据的最佳方法是什么?

2024-03-29 09:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新手,我试图找到验证数据的最佳方法。在

我有一个“well”类型的对象,它具有其他对象的属性。也可以通过XML文件来获取数据。下面是一个例子。在


class Well:
    def __init__ (self, name, group):
        self.__name   = name     # Required
        self.__group  = group    # Required
        self.__operate_list = [] # Optional
        self.__monitor_list = [] # Optional
        self.__geometry = None   # Optional
        self.__perf = None       # Optional
        ...

class Operate:

    # *OPERATE (*MAX|*MIN) type value (action)
    # *OPERATE (*PENALTY) type (mode) value (action)
    # *OPERATE (*WCUTBACK) type mode v1 (v2 (v3)) (action)

    def __init__ (self, att:str, type_:str, value: [], mode=None, action=None):
        self.__att = att
        self.__type_ = type_
        self.__mode = mode
        self.__value_list = value
        self.__action = action        

例如,为了验证“operate”,我需要检查每个属性的大量限制和有效值。例如,我有一个有效的“type”字符串列表,我应该断言type_u在这个列表中。在

1)最好的方法是在构造函数中?我应该创建一个方法来进行验证吗?还是应该创建一个新类来验证数据?在

2)我应该在哪里创建这些有效值列表?在构造函数中?作为全局变量?在


Tags: 数据方法nameselfnone列表valuemode
3条回答

你可以用描述符来做。我能设计的唯一优点是它将验证放在另一个类中—使使用它的类不那么冗长。不幸的是,您必须为每个属性创建一个具有唯一验证的属性,除非您希望包含成员资格测试和/或测试实例的选项,这些选项不应使其变得太复杂。在

from weakref import WeakKeyDictionary

class RestrictedAttribute:
    """A descriptor that restricts values"""
    def __init__(self, restrictions):
        self.restrictions = restrictions
        self.data = WeakKeyDictionary()

    def __get__(self, instance, owner):
        return self.data.get(instance, None)

    def __set__(self, instance, value):
        if value not in self.restrictions:
            raise ValueError(f'{value} is not allowed')
        self.data[instance] = value

使用时,必须将描述符实例指定为类属性

^{pr2}$

使用中:

In [15]: o = Operate('f',type_='blue',value=[1,2])

In [16]: o._Operate__type_
Out[16]: 'blue'

In [17]: o._Operate__type_ = 'green'
Traceback (most recent call last):

  File "<ipython-input-17-b412cfaa0cb0>", line 1, in <module>
    o._Operate__type_ = 'green'

  File "P:/pyProjects3/tmp1.py", line 28, in __set__
    raise ValueError(msg)

ValueError: green is not allowed
assert isinstance(obj) 

是如何测试对象的类型。在

^{pr2}$

是如何测试对象是否在容器中。在

不管是在init方法中还是在其他方法中执行,这取决于您觉得哪个方法更干净,或者您是否需要重用该功能。在

有效值列表可以传递到init方法或硬编码到init方法。它也可以是类的全局属性。在

您可以通过使用property函数来使用getter和setter方法:

class Operate:
    def __init__(self, type):
        self.type = type

    @property
    def type(self):
        return self._type

    @type.setter
    def type(self, value):
        assert value in ('abc', 'xyz')
        self._type = value

因此:

^{pr2}$

会导致:

Traceback (most recent call last):
  File "test.py", line 18, in <module>
    o = Operate(type='123')
  File "test.py", line 8, in __init__
    self.type = type
  File "test.py", line 15, in type
    assert value in ('abc', 'xyz')
AssertionError

相关问题 更多 >