Python没有类似于Java的private
关键字, 但也可以为类定义私有属性. 只需将属性命名变为以__
开头, 例如 __field
.
示例代码:
class Vector2D(object):
def __init__(self, x, y):
self.__x = float(x)
self.__y = float(y)
self.xx = x
self.yy = y
def get_x(self):
return self.__x # 内部访问
if __name__ == "__main__":
v = Vector2D(3, 4)
print v.__dict__
print v._Vector2D__x, v.get_x()# 但是可以通过v._Vector2D__x 在外部访问
v.__x # 外部访问
输出:
{'yy': 4, 'xx': 3, '_Vector2D__x': 3.0, '_Vector2D__y': 4.0}
3.0 3.0
Traceback (most recent call last):
...
v.__x
AttributeError: 'Vector2D' object has no attribute '__x'
从上面的例子可以看出:
1. __field
被编译器重命名为_className__field
2. 在class外部不能访问obj.__field
, 但在class内部可以
3. 但是, 这只能防止无意间的调用, 不能防止恶意调用, 用Fluent Python的话来讲, 这是一种safety device, not security device
, 用国语来讲, 就是防君子不防xx
, 因为可以通过obj._className__field
在外部访问obj
的私有__field
.
Reference
Fluent Python, Chapter 9