python的偽私人屬性

來源:互聯網
上載者:User

標籤:his   AC   bsp   為什麼   tool   post   屬性   成員變數   不同   

偽私人屬性

類Example中定義的變數__X會自動變成_Example__X, 變數前有雙底線的變數被稱為偽私人屬性,為什麼叫偽私人屬性呢?因為該屬性並不是私人不可改變的,在類外依舊可以通過 _類名__變數名  來調用修改該屬性,那為什麼需要偽私人屬性的存在呢?先舉例一段代碼來說明

 1 class C1: 2     def meth1(self): 3         self.X=88 4     def meth2(self): 5         print(self.X) 6  7 class C2: 8     def metha(self): 9         self.X=9910     def methb(self):11         print(self.X)12 13 class C3(C1,C2):14     pass15 16 I=C3()17 I.meth1()18 I.metha()19 20 I.meth2()21 I.methb()22 print(I.__dict__)23 24 I._C1__X=322    #修改偽私人屬性25 print(I.__dict__)26 27 # 9928 # 9929 # {‘X‘: 99}30 # {‘X‘: 99, ‘_C1__X‘: 322}

假如類1和類2分別由程式員A和B所編寫,當兩個類混合在一起時,每個類的self.X得到的值取決於最後賦值的類,並不能實現本身的意義(兩個程式員對自己分別編寫的meth1和metha方法中X的賦值是取不同值,而並非希望類混合後X的取值相同),因而此時若兩人使用的是偽私人變數就不會出現這種情況,如下:

 1 class C1: 2     def meth1(self): 3         self.__X=88 4     def meth2(self): 5         print(self.__X) 6  7 class C2: 8     def metha(self): 9         self.__X=9910     def methb(self):11         print(self.__X)12 13 class C3(C1,C2):14     pass15 16 I=C3()17 I.meth1()18 I.metha()19 20 I.meth2()21 I.methb()22 print(I.__dict__)23 I._C1__X=32224 print(I.__dict__)25 26 # 8827 # 9928 # {‘_C2__X‘: 99, ‘_C1__X‘: 88}29 # {‘_C2__X‘: 99, ‘_C1__X‘: 322}

如上避免了執行個體中潛在的變數名衝突

 

進一步舉例

 1 class Super: 2     def method(self): 3         print(‘this is method Super‘) 4  5 class Tool: 6     def __method(self): 7         print(‘this is method Tool‘) 8     def other(self): 9         print(‘calling method __method‘)10         self.__method()11 12 class Sub1(Tool,Super):13     def actions(self):14         self.method()15 16 class Sub2(Tool):17     def __init__(self):18         self.method=9919         print(self.method)20 21 I1=Tool()22 I1.other()23 print(‘************‘)24 I2=Sub1()25 I2.actions()26 #對類繼承樹的搜尋調用method的順序本是在Tool類中搜尋再在類Super中搜尋27 #但因類Tool類中method為偽私人方法並不能在Tool類外調用,因而Tool類中method方法被隱藏28 #再到類Super中搜尋,因Super類中method方法未私人化,而調用了Super類中method方法29 print(‘-----------------‘)30 I2.other() #繼承樹中搜尋other方法並未被Tool類私人化,從而能通過類中other方法調用私人方法__method31 print(‘***************‘)32 I3=Sub2()33 #執行個體化Sub2方法已不再是對父類Tool中method方法的重寫,而是建立一新成員變數method34 35 # calling method __method36 # this is method Tool37 # ************38 # this is method Super39 # -----------------40 # calling method __method41 # this is method Tool42 # ***************43 # 99

 

python的偽私人屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.