擅长:python、mysql、java
<p>你可以用描述符来做。我能设计的唯一优点是它将验证放在另一个类中—使使用它的类不那么冗长。不幸的是,您必须为每个属性创建一个具有唯一验证的属性,除非您希望包含成员资格测试和/或测试实例的选项,这些选项不应使其变得太复杂。在</p>
<pre><code>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
</code></pre>
<p>使用时,必须将描述符实例指定为类属性</p>
^{pr2}$
<p>使用中:</p>
<pre><code>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
</code></pre>