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

 总结:类的私有属性,不要看得太加复杂相当于,一个对象有私有属性,给他加上私有标签,调用时加上私有标签就行了。

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