例如:
class Example:
def __init__(self, value):
self.value = value
我想这样做,以便人们无法改变self.value
在初始化之后的内容。如果有人尝试过,它会引发异常:
>>> c = Example(1)
>>> c.value = 2
我希望它引发错误或者只是让它变得不可能。
答案 0 :(得分:2)
您可以使用property:
class Example(object):
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
请注意,该值仍可写为example_object._value
,但是将下划线添加到属性名称是一种约定,用于告知其他开发人员此属性不属于类公共API的一部分,因此不应使用。< / p>