擅长:python、mysql、java
<p>通过使用属性可以使它不可写(与不可变有细微的不同),但是没有办法使它私有化——这违背了Python的哲学。</p>
<pre><code>class Foo(object): # don't need 'object' in Python 3
@property
def thingies(self):
return 'thing1', 'thing2', 'thing3'
f = Foo()
print f.thingies
#('thing1', 'thing2', 'thing3')
f.thingies = 9
#Traceback (most recent call last):
# File "test.py", line 8, in <module>
# f.thingies = 9
#AttributeError: can't set attribute
</code></pre>
<p>它是否是不可变的取决于您返回的内容;如果您返回一个可变的对象,您可能能够对<em>和</em>进行变异,使这些更改显示在实例/类中。</p>
<pre><code>class FooMutable(object):
_thingies = [1, 2, 3]
@property
def thingies(self):
return self._thingies
foo = FooMutable()
foo.thingies.append(4)
print foo.thingies
# [1, 2, 3, 4]
</code></pre>
<p>这将允许您对<code>thingies</code>进行变异,并且由于返回的对象与实例/类中保留的对象相同,因此更改将反映在后续访问中。</p>
<p>比较一下:</p>
<pre><code>class FooMutable(object):
@property
def thingies(self):
return [1, 2, 3]
foo = FooMutable()
foo.thingies.append(4)
print foo.thingies
# [1, 2, 3]
</code></pre>
<p>因为每次都会返回一个全新的列表,所以对它的更改不会反映在后续的访问中。</p>