Python中私有屬性“_“下劃線和“__“雙下劃線區(qū)別
在Python中,使用一個下劃線(_)和兩個下劃線(__)來表示私有屬性。
1、一個下劃線
一個下劃線的屬性名(例如 _x)表示這個屬性是受保護的,應該被視為私有屬性,盡管它仍然可以被類的實例直接訪問。受保護的屬性被視為僅供內(nèi)部使用,并且應該被子類和外部代碼視為不可訪問的。但是,它們可以被子類和外部代碼直接訪問。
2、兩個下劃線
兩個下劃線的屬性名(例如 __x)表示這個屬性是真正的私有屬性。這意味著在類的外部無法直接訪問該屬性,甚至子類也不能訪問它。Python會自動將這個屬性名重命名為 _classname__x 的形式,以避免命名沖突。
3、代碼示例
class MyClass: def __init__(self): self.public_attribute = "I am a public attribute" self._protected_attribute = "I am a protected attribute" self.__private_attribute = "I am a private attribute" def print_attributes(self): print(self.public_attribute) print(self._protected_attribute) print(self.__private_attribute) obj = MyClass() # Accessing public attribute print(obj.public_attribute) # Accessing protected attribute print(obj._protected_attribute) # Accessing private attribute using its mangled name print(obj._MyClass__private_attribute) # Printing all attributes using method obj.print_attributes() # Accessing private attribute # This will raise an AttributeError print(obj.__private_attribute)
輸出結(jié)果
I am a public attribute
I am a protected attribute
I am a private attribute
I am a public attribute
I am a protected attribute
I am a private attribute
AttributeError: 'MyClass' object has no attribute '__private_attribute'
可以看到,Python中使用下劃線和雙下劃線來表示不同級別的屬性訪問限制。在使用時,應該遵循一定的規(guī)范和約定,以便代碼能夠更加清晰和易于維護。
到此這篇關(guān)于Python中私有屬性“_“下劃線和“__“雙下劃線區(qū)別的文章就介紹到這了,更多相關(guān)Python 下劃線和雙下劃線內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入理解Python虛擬機中字典(dict)的實現(xiàn)原理及源碼剖析
這篇文章主要介紹了在?cpython?當中字典的實現(xiàn)原理,在本篇文章當中主要介紹在早期?python3?當中的版本字典的實現(xiàn),現(xiàn)在的字典做了部分優(yōu)化,希望對大家有所幫助2023-03-03python 禁止函數(shù)修改列表的實現(xiàn)方法
下面小編就為大家?guī)硪黄猵ython 禁止函數(shù)修改列表的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08用Python把csv文件批量修改編碼為UTF-8格式并轉(zhuǎn)為Excel格式的方法
有時候用excel打開一個csv文件,中文全部顯示亂碼,然后手動用notepad++打開,修改編碼為utf-8并保存后,再用excel打開顯示正常,本文將給大家介紹一下用Python把csv文件批量修改編碼為UTF-8格式并轉(zhuǎn)為Excel格式的方法,需要的朋友可以參考下2023-09-09Python中str is not callable問題詳解及解決辦法
這篇文章主要介紹了Python中str is not callable問題詳解及解決辦法的相關(guān)資料,需要的朋友可以參考下2017-02-02python網(wǎng)絡編程學習筆記(九):數(shù)據(jù)庫客戶端 DB-API
這篇文章主要介紹了python 數(shù)據(jù)庫客戶端 DB-API的相關(guān)資料,需要的朋友可以參考下2014-06-06使用PyInstaller將Pygame庫編寫的小游戲程序打包為exe文件及出現(xiàn)問題解決方法
這篇文章主要介紹了使用PyInstaller將Pygame庫編寫的小游戲程序打包為exe文件的方法,給大家介紹了通過Pyinstaller打包Pygame庫寫的小游戲程序出現(xiàn)的問題及解決方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09