Python 私有化操作例項分析
阿新 • • 發佈:2020-01-09
本文例項講述了Python 私有化操作。分享給大家供大家參考,具體如下:
私有化
xx: 公有變數
_x: 單前置下劃線,私有化屬性或方法,from somemodule import *禁止匯入,類物件和子類可以訪問
_xx:雙前置下劃線,避免與子類中的屬性命名衝突,無法在外部直接訪問(名字重整所以訪問不到)
xx:雙前後下劃線,使用者名稱字空間的魔法物件或屬性。例如:init,__ 不要自己發明這樣的名字
xx:單後置下劃線,用於避免與Python關鍵詞的衝突
通過name mangling(名字重整(目的就是以防子類意外重寫基類的方法或者屬性)如:_Class__object)機制就可以訪問private了。
#coding=utf-8 class Person(object): def __init__(self,name,age,taste): self.name = name self._age = age self.__taste = taste def showperson(self): print(self.name) print(self._age) print(self.__taste) def dowork(self): self._work() self.__away() def _work(self): print('my _work') def __away(self): print('my __away') class Student(Person): def construction(self,taste): self.name = name self._age = age self.__taste = taste def showstudent(self): print(self.name) print(self._age) print(self.__taste) @staticmethod def testbug(): _Bug.showbug() # 模組內可以訪問,當from cur_module import *時,不匯入 class _Bug(object): @staticmethod def showbug(): print("showbug") s1 = Student('jack',25,'football') s1.showperson() print('*'*20) # 無法訪問__taste,導致報錯 # s1.showstudent() s1.construction('rose',30,'basketball') s1.showperson() print('*'*20) s1.showstudent() print('*'*20) Student.testbug()
總結
父類中屬性名為__名字的,子類不繼承,子類不能訪問
如果在子類中向__名字賦值,那麼會在子類中定義的一個與父類相同名字的屬性
_名的變數、函式、類在使用from xxx import *
時都不會被匯入
更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python面向物件程式設計入門與進階教程》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python編碼操作技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程式設計有所幫助。