Python 私有化操作實例分析
本文實例講述了Python 私有化操作。分享給大家供大家參考,具體如下:
私有化
xx: 公有變量
_x: 單前置下劃線,私有化屬性或方法,from somemodule import *禁止導(dǎo)入,類對象和子類可以訪問
_xx:雙前置下劃線,避免與子類中的屬性命名沖突,無法在外部直接訪問(名字重整所以訪問不到)
xx:雙前后下劃線,用戶名字空間的魔法對象或?qū)傩?。例?init , __ 不要自己發(fā)明這樣的名字
xx:單后置下劃線,用于避免與Python關(guān)鍵詞的沖突
通過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, name, age, 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() # 模塊內(nèi)可以訪問,當(dāng)from cur_module import *時,不導(dǎo)入 class _Bug(object): @staticmethod def showbug(): print("showbug") s1 = Student('jack', 25, 'football') s1.showperson() print('*'*20) # 無法訪問__taste,導(dǎo)致報錯 # s1.showstudent() s1.construction('rose', 30, 'basketball') s1.showperson() print('*'*20) s1.showstudent() print('*'*20) Student.testbug()
總結(jié)
父類中屬性名為__名字的,子類不繼承,子類不能訪問
如果在子類中向__名字賦值,那么會在子類中定義的一個與父類相同名字的屬性
_名的變量、函數(shù)、類在使用from xxx import *
時都不會被導(dǎo)入
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計入門與進階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
pandas.DataFrame刪除/選取含有特定數(shù)值的行或列實例
今天小編就為大家分享一篇pandas.DataFrame刪除/選取含有特定數(shù)值的行或列實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11pyppeteer執(zhí)行js繞過webdriver監(jiān)測方法上
這篇文章主要為大家介紹了pyppeteer執(zhí)行js繞過webdriver監(jiān)測方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2022-04-04Python中使用pprint函數(shù)進行格式化輸出的教程
這篇文章主要介紹了Python中使用pprint函數(shù)進行格式化輸出的教程,包括能夠控制輸出寬度等非常有用的特性,需要的朋友可以參考下2015-04-04Python實現(xiàn)Matplotlib,Seaborn動態(tài)數(shù)據(jù)圖的示例代碼
這篇文章主要為大家詳細介紹了如何讓Matplotlib、Seaborn的靜態(tài)數(shù)據(jù)圖動起來,變得栩栩如生。文中的示例代碼講解詳細,感興趣的小伙伴可以學(xué)習(xí)一下2022-05-05對Keras中predict()方法和predict_classes()方法的區(qū)別說明
這篇文章主要介紹了對Keras中predict()方法和predict_classes()方法的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06