第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 python 中驗證數(shù)據(jù)的最佳方法是什么?

在 python 中驗證數(shù)據(jù)的最佳方法是什么?

偶然的你 2022-05-11 16:29:12
我是 Python 的新手,我正在努力尋找驗證數(shù)據(jù)的最佳方法。我有一個“well”類型的對象,它具有其他對象的屬性。數(shù)據(jù)可以來自 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_”字符串列表,我應(yīng)該斷言 type_ 在這個列表中。1)最好的方法是在構(gòu)造函數(shù)中?我應(yīng)該創(chuàng)建一種方法來進行此驗證嗎?或者我應(yīng)該創(chuàng)建一個僅用于驗證數(shù)據(jù)的新類嗎?2) 我應(yīng)該在哪里創(chuàng)建這些有效值列表?在構(gòu)造函數(shù)中?作為全局變量?
查看完整描述

3 回答

?
富國滬深

TA貢獻1790條經(jīng)驗 獲得超9個贊

您可以通過使用以下property函數(shù)來使用 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

以便:


o = Operate(type='123')

會導(dǎo)致:


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


查看完整回答
反對 回復(fù) 2022-05-11
?
拉風的咖菲貓

TA貢獻1995條經(jīng)驗 獲得超2個贊

assert isinstance(obj)

是你如何測試一個對象的類型。

if item in container: ...

是如何測試對象是否在容器中。

是在init方法中還是在其他方法中執(zhí)行此操作取決于您,這取決于您看起來更清潔,或者您是否需要重用該功能。

有效值列表可以傳遞到init方法或硬編碼到init方法中。它也可以是類的全局屬性。


查看完整回答
反對 回復(fù) 2022-05-11
?
倚天杖

TA貢獻1828條經(jīng)驗 獲得超3個贊

你可以用描述符來做到這一點。我可以設(shè)計的唯一優(yōu)點是將驗證放在另一個類中 - 使使用它的類不那么冗長。不幸的是,您必須為每個屬性制作一個具有唯一驗證的屬性,除非您想包含成員資格測試和/或測試實例的選項,這不應(yīng)該使其過于復(fù)雜。


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

使用時,必須將描述符實例分配為類屬性


class Operate:


    __type_ = RestrictedAttribute(('red','blue'))


    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        

正在使用:


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


查看完整回答
反對 回復(fù) 2022-05-11
  • 3 回答
  • 0 關(guān)注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號