3 回答

TA貢獻(xiàn)1790條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以通過(guò)使用以下property函數(shù)來(lái)使用 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')
會(huì)導(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

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
assert isinstance(obj)
是你如何測(cè)試一個(gè)對(duì)象的類型。
if item in container: ...
是如何測(cè)試對(duì)象是否在容器中。
是在init方法中還是在其他方法中執(zhí)行此操作取決于您,這取決于您看起來(lái)更清潔,或者您是否需要重用該功能。
有效值列表可以傳遞到init方法或硬編碼到init方法中。它也可以是類的全局屬性。

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
你可以用描述符來(lái)做到這一點(diǎn)。我可以設(shè)計(jì)的唯一優(yōu)點(diǎn)是將驗(yàn)證放在另一個(gè)類中 - 使使用它的類不那么冗長(zhǎng)。不幸的是,您必須為每個(gè)屬性制作一個(gè)具有唯一驗(yàn)證的屬性,除非您想包含成員資格測(cè)試和/或測(cè)試實(shí)例的選項(xiàng),這不應(yīng)該使其過(guò)于復(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
使用時(shí),必須將描述符實(shí)例分配為類屬性
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
添加回答
舉報(bào)