歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python的私有變量解析

Python的私有變量解析

日期:2017/3/1 9:44:58   编辑:Linux編程

在內的內部定義並使用,外部無法訪問,以雙下劃線作為前作,定義後被python轉為_classname__變量名了

--------------------------------------------------------------------------------------
In [1]: class aa:
...: __x = 12 #私有變量_ _x
...: def px(self):
...: print 'private __x', aa.__x #內部訪問
...:

In [2]: a = aa()

In [3]: a.px()
private __x 12

In [4]: dir(a)
Out[4]: ['__doc__', '__module__', '_aa__x', 'px'] # map成_classname__變量名了

In [5]: a.__x = 13#實例對象a的實例變量

In [6]: dir(a)
Out[6]: ['__doc__', '__module__', '__x', '_aa__x', 'px']

In [7]: print a.__x
13

In [8]:In [8]: print aa.__x
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-34f87438b5b5> in <module>()
----> 1 print aa.__x

AttributeError: class aa has no attribute '__x'

In [9]:
-----------------------------------------------------------

推薦閱讀:

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved