<p>在Python中,惯例是在属性名上使用<code>_</code>前缀表示<code>protected</code>,使用<code>__</code>前缀表示<code>private</code>。这不是由语言强制的;程序员应该知道不要编写依赖于非公共数据的代码。</p>
<p>如果您真的想强制执行不变性,那么可以使用元类<sup>[<a href="http://docs.python.org/reference/datamodel.html#customizing-class-creation">docs</a>]</sup>(类的类)。只要修改<code>__setattr__</code>和<code>__delattr__</code>以在有人试图修改它时引发异常,并将其设为<code>tuple</code>(不可变列表)<sup>[<a href="http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences">docs</a></sup>。</p>
<pre><code>class FooMeta(type):
"""A type whose .thingies attribute can't be modified."""
def __setattr__(cls, name, value):
if name == "thingies":
raise AttributeError("Cannot modify .thingies")
else:
return type.__setattr__(cls, name, value)
def __delattr__(cls, name):
if name == "thingies":
raise AttributeError("Cannot delete .thingies")
else:
return type.__delattr__(cls, name)
thing1, thing2, thing3 = range(3)
class Foo(object):
__metaclass__ = FooMeta
thingies = (thing1, thing2, thing3)
other = [1, 2, 3]
</code></pre>
<h3>示例</h3>
<pre><code>print Foo.thingies # prints "(0, 1, 2)"
Foo.thingies = (1, 2) # raises an AttributeError
del Foo.thingies # raise an AttributeError
</code></pre>
<pre><code>Foo.other = Foo.other + [4] # no exception
print Foo.other # prints "[1, 2, 3, 4]"
</code></pre>
<p>从技术上讲,仍然可以通过类的内部<code>.__dict__</code>属性来修改这些属性,但这应该足以阻止大多数用户,很难完全保护Python对象。</p>