Centos7中python使用類屬性的私有輸出

最近學習Python的利用,擴展記錄一下類的私有屬性定義。

演示實例:

創建一個py文件,寫入一個類屬性的私有化。

#vim private.py

  1 class Test(object):
  2     def __init__(self):
  3         self.__num=110#類屬性的私有化
  4 
  5 t = Test()
  6 print (t.__num)#輸出類的私有屬性
  

保存測試類私有屬性出書

[root@localhost day01]# vim  private.py 
[root@localhost day01]# python3 private.py 
Traceback (most recent call last):
  File "private.py", line 6, in <module>
    print (t.__num)
AttributeError: 'Test' object has no attribute '__num'

#報錯,對象Test沒有屬性__num.因爲屬性已經被加了__私有化。如果改成輸出是t._Test__num就可以正常輸出。爲什麼。看下面!

#vim private.py(再次編輯將後面兩行註釋掉)

  1 class Test(object):
  2     def __init__(self):
  3         self.__num=110#類屬性的私有化。
  4 
  5 #t = Test()
  6 #print (t.__num)#輸出類的私有屬性

 

[root@localhost day01]# ipython3 
/usr/python-3.4.6/lib/python3.4/site-packages/IPython/core/history.py:226: UserWarning: IPython History requires SQLite, your history will not be saved
  warn("IPython History requires SQLite, your history will not be saved")
Python 3.4.6 (default, Jan 24 2019, 11:20:45) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import private

In [2]: t = Test() #不能直接將類直接賦值給變量。
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-57ee07e6cc45> in <module>()
----> 1 t = Test()

NameError: name 'Test' is not defined

In [3]: t = private.Test()#必須加上文件名字

In [4]: dir(t)  #查看對象中的類屬性、方法等用dir(x)
Out[4]: 
['_Test__num', #對象前面加上_表示已經對象重組,實際就是改名字。直接引用t.Test__num不行。要用t._Test__num;
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']

In [5]: 

In [5]: t._Test__num #使用t,_Test__num可以輸出,或者將private文件中輸出改成print(t._Test__num)
Out[5]: 110

 總結:類的私有屬性,不要看得太加複雜相當於,一個對象有私有屬性,給他加上私有標籤,調用時加上私有標籤就行了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章