1. 使用`@property`装饰器:
```python
class V:
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
v = V(5)
print(v.x) 输出 5
v.x = 4 AttributeError: can't set attribute
2. 使用双下划线前缀(名称改写):
```python
class V:
def __init__(self, x):
self.__x = x
v = V(5)
print(v.__x) 输出 5
v.__x = 4 AttributeError: 'V' object has no attribute '__x'
3. 使用单下划线前缀(虽然这并不是真正的私有属性,只是一种命名习惯,表示属性是受保护的):
```python
class V:
def __init__(self, x):
self._x = x
v = V(5)
print(v._x) 输出 5
v._x = 4 正常工作
4. 使用两个下划线前缀(真正的私有属性,Python会在属性名前添加类名和下划线来重命名):
```python
class V:
def __init__(self, x):
self.__x = x
v = V(5)
print(v.__dict__["__V__x"]) 输出 5
v.__x = 4 AttributeError: 'V' object has no attribute '__x'
5. 使用自定义属性规则,例如只允许通过特定方法修改属性值:
```python
class V:
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
@x.setter
def x(self, value):
if isinstance(value, (int, float)):
self._x = value
else:
raise ValueError("x must be a number")
v = V(5)
print(v.x) 输出 5
v.x = 4 正常工作
v.x = "not a number" 抛出 ValueError
以上方法可以帮助你保护类的属性,防止外部代码随意修改属性值。需要注意的是,Python并没有像Java或C++那样的显式`private`关键字,它使用名称改写技术来模拟私有属性。