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 <module>
p.__inaccessible()
AttributeError: Secretive instance has no attribute '__inaccessible'
>>>
上面的紅色字體,表示類外部訪問私有屬性時報的錯誤
其實要訪問,也是可以的,但我們一般不這麼做,例如:
>>> p._Secretive__inaccessible()
this secret method
簡而言之,確保其他人不能訪問對象的方法和特性是不可能的,如果我們真想使用這種方法但是又不想讓其他對象不要訪問內部數據,一般是這樣做,可以使用單下劃線,例如前面的例子中__inaccessible(self) 就可以用單下劃線(_inaccessible(self))來表示,這也算是個好習慣,的確有實際效果。
(原因:帶下劃線的名字都不會被帶星號的imports(from module import *)語句導入)