在 Python 中,约定是使用_
属性名称前缀的含义protected
and a __
前缀表示意思private
。这不是由语言强制执行的;而是由语言强制执行的。程序员应该知道不要编写依赖于非公开数据的代码。
If you really wanted to enforce immutability, you could use a metaclass[docs http://docs.python.org/reference/datamodel.html#customizing-class-creation] (the class of a class). Just modify __setattr__
and __delattr__
to raise exceptions when someone attempts to modify it, and make it a tuple
(an immutable list) [docs http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences].
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]
Examples
print Foo.thingies # prints "(0, 1, 2)"
Foo.thingies = (1, 2) # raises an AttributeError
del Foo.thingies # raise an AttributeError
Foo.other = Foo.other + [4] # no exception
print Foo.other # prints "[1, 2, 3, 4]"
从技术上讲,仍然可以通过类的内部来修改它们.__dict__
属性,但这应该足以阻止大多数用户,完全保护 Python 对象是非常困难的。