歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python 類私有成員

Python 類私有成員

日期:2017/3/1 10:15:35   编辑:Linux編程

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

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

  1. '''''
  2. Created on 2012-7-24
  3. @author: Administrator
  4. '''
  5. class Test:
  6. def test_1(self):
  7. print 'test_1 is ok....'
  8. def __test_2(self):
  9. print 'test_2 is ok...'
  10. test = Test()
  11. test.test_1()
  12. 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'

Copyright © Linux教程網 All Rights Reserved