Python 本身是并直接支持私有的方式,但我们自己可以通过修改外部特性来达到这个目的,在类的内部定义中使用双下划线命名,下面看一下具体代码:
class Secretive:
def __inaccessible(self):
print "this secret method"
def accessible(self):
print "publlic method"
self.__inaccessible() #类部内访问及私有属性
p = Secretive()
p.accessible()
p.__inaccessible() #类外部访问及私有属性,这里将会报错请注意
执行结果:
>>>
publlic method
this secret method
Traceback (most recent call last):
File "C:/Python27/test.py", line 12, in
p.__inaccessible()
AttributeError: Secretive instance has no attribute '__inaccessible'
>>>
上面的红色字体,表示类外部访问私有属性时报的错误
其实要访问,也是可以的,但我们一般不这么做,例如:
>>> p._Secretive__inaccessible()
this secret method
简而言之,确保其他人不能访问对象的方法和特性是不可能的,如果我们真想使用这种方法但是又不想让其他对象不要访问内部数据,一般是这样做,可以使用单下划线,例如前面的例子中__inaccessible(self) 就可以用单下划线(_inaccessible(self))来表示,这也算是个好习惯,的确有实际效果。
(原因:带下划线的名字都不会被带星号的imports(from module import *)语句导入)