擅长:python、mysql、java
<p>您可以通过使用<code>property</code>函数来使用getter和setter方法:</p>
<pre><code>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
</code></pre>
<p>因此:</p>
^{pr2}$
<p>会导致:</p>
<pre><code>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
</code></pre>