猿问

在 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        

例如,要验证“操作”,我需要检查每个属性的许多限制和有效值。例如,我有一个有效的“type_”字符串列表,我应该断言 type_ 在这个列表中。


1)最好的方法是在构造函数中?我应该创建一种方法来进行此验证吗?或者我应该创建一个仅用于验证数据的新类吗?


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


偶然的你
浏览 142回答 3
3回答

富国沪深

您可以通过使用以下property函数来使用 getter 和 setter 方法:class Operate:&nbsp; &nbsp; def __init__(self, type):&nbsp; &nbsp; &nbsp; &nbsp; self.type = type&nbsp; &nbsp; @property&nbsp; &nbsp; def type(self):&nbsp; &nbsp; &nbsp; &nbsp; return self._type&nbsp; &nbsp; @type.setter&nbsp; &nbsp; def type(self, value):&nbsp; &nbsp; &nbsp; &nbsp; assert value in ('abc', 'xyz')&nbsp; &nbsp; &nbsp; &nbsp; self._type = value以便:o = Operate(type='123')会导致:Traceback (most recent call last):&nbsp; File "test.py", line 18, in <module>&nbsp; &nbsp; o = Operate(type='123')&nbsp; File "test.py", line 8, in __init__&nbsp; &nbsp; self.type = type&nbsp; File "test.py", line 15, in type&nbsp; &nbsp; assert value in ('abc', 'xyz')AssertionError

拉风的咖菲猫

assert&nbsp;isinstance(obj)是你如何测试一个对象的类型。if&nbsp;item&nbsp;in&nbsp;container:&nbsp;...是如何测试对象是否在容器中。是在init方法中还是在其他方法中执行此操作取决于您,这取决于您看起来更清洁,或者您是否需要重用该功能。有效值列表可以传递到init方法或硬编码到init方法中。它也可以是类的全局属性。

倚天杖

你可以用描述符来做到这一点。我可以设计的唯一优点是将验证放在另一个类中 - 使使用它的类不那么冗长。不幸的是,您必须为每个属性制作一个具有唯一验证的属性,除非您想包含成员资格测试和/或测试实例的选项,这不应该使其过于复杂。from weakref import WeakKeyDictionaryclass RestrictedAttribute:&nbsp; &nbsp; """A descriptor that restricts values"""&nbsp; &nbsp; def __init__(self, restrictions):&nbsp; &nbsp; &nbsp; &nbsp; self.restrictions = restrictions&nbsp; &nbsp; &nbsp; &nbsp; self.data = WeakKeyDictionary()&nbsp; &nbsp; def __get__(self, instance, owner):&nbsp; &nbsp; &nbsp; &nbsp; return self.data.get(instance, None)&nbsp; &nbsp; def __set__(self, instance, value):&nbsp; &nbsp; &nbsp; &nbsp; if value not in self.restrictions:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise ValueError(f'{value} is not allowed')&nbsp; &nbsp; &nbsp; &nbsp; self.data[instance] = value使用时,必须将描述符实例分配为类属性class Operate:&nbsp; &nbsp; __type_ = RestrictedAttribute(('red','blue'))&nbsp; &nbsp; def __init__ (self, att:str, type_:str, value: [], mode=None, action=None):&nbsp; &nbsp; &nbsp; &nbsp; self.__att = att&nbsp; &nbsp; &nbsp; &nbsp; self.__type_ = type_&nbsp; &nbsp; &nbsp; &nbsp; self.__mode = mode&nbsp; &nbsp; &nbsp; &nbsp; self.__value_list = value&nbsp; &nbsp; &nbsp; &nbsp; self.__action = action&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;正在使用: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):&nbsp; File "<ipython-input-17-b412cfaa0cb0>", line 1, in <module>&nbsp; &nbsp; o._Operate__type_ = 'green'&nbsp; File "P:/pyProjects3/tmp1.py", line 28, in __set__&nbsp; &nbsp; raise ValueError(msg)ValueError: green is not allowed
随时随地看视频慕课网APP

相关分类

Python
我要回答