1. 程式人生 > >python私有方法和私有屬性屬性理解

python私有方法和私有屬性屬性理解

__init__ out code 避免 col 系統 import name sizeof

私有屬性、方法——Python並沒有真正的私有化支持,但可用下劃線得到偽私有
盡量避免定義以下劃線開頭的變量
(1)_xxx "單下劃線 " 開始的成員變量叫做保護變量,意思是只有類對象(即類實例)和子類對象自己能訪問到這些變量,需通過類提供的接口進行訪問;不能用‘from module import *‘導入
(2)__xxx 類中的私有變量/方法名 (Python的函數也是對象,所以成員方法稱為成員變量也行得通。)," 雙下劃線 " 開始的是私有成員,意思是只有類對象自己能訪問,連子類對象也不能訪問到這個數據。
(3)__xxx__ 系統定義名字,前後均有一個“雙下劃線” 代表python裏特殊方法專用的標識,如 __init__() 代表類的構造函數。

In [6]: class Dog():
   ...:     def __sit_down(self):
   ...:         print(坐下了)
   ...:     def sit_down(self,host_name):
   ...:         if host_name==主人:
   ...:             self.__sit_down()

In [7]: w=Dog()

In [8]: w.sit_down(主人)
坐下了

In [9]: w.sit_down()

In [10]: w.__sit_down()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-16df8360e9bf> in <module>() ----> 1 w.__sit_down() AttributeError: Dog object has no attribute __sit_down In [13]: w._Dog__sit_down() 坐下了

python實例可以直接調用Python的公有方法;私有方法和屬性在外部不可以直接用屬性或方法名調用,內部將私有方法和屬性在前面增加了 "_類名"

                           
In [14]: dir(Dog)          
Out[
14]: [‘_Dog__sit_down‘, __class__, __delattr__, __dict__, __dir__, __doc__, __eq__, __format__, __ge__, __getattribute__, __gt__, __hash__, __init__, __init_subclass__, __le__, __lt__, __module__, __ne__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__, __weakref__, ‘sit_down‘]

python私有方法和私有屬性屬性理解