1. 程式人生 > >python 類私有成員

python 類私有成員

Python中預設的成員函式,成員變數都是公開的(public),而且python中沒有類似public,private等關鍵詞來修飾成員函式,成員變數。

在python中定義私有變數只需要在變數名或函式名前加上 ”__“兩個下劃線,那麼這個函式或變數就會為私有的了。、

'''
Created on 2012-7-24

@author: Administrator
'''
class Test:
    def test_1(self):
        print 'test_1 is ok....'
        
    def __test_2(self):
        print 'test_2 is ok...'

test = Test()
test.test_1()
test.__test_2()

執行結果:

test_1 is ok....
Traceback (most recent call last):
  File "D:\Install\Eclipse\WorkSpace\Python\test_class.py", line 15, in <module>
    test.__test_2()
AttributeError: Test instance has no attribute '__test_2'