Python——私人化 和 屬性property

來源:互聯網
上載者:User

標籤:重寫   自己   code   總結   mod   sel   property   name   定義   

Python——私人化 和 屬性property

一、私人化

  • xx: 公有變數
  • _x: 單前置底線,私人化屬性或方法,from somemodule import *禁止匯入,類對象和子類可以訪問
  • __xx:雙前置底線,避免與子類中的屬性命名衝突,無法在外部直接存取(名字重整所以訪問不到)
  • __xx__:雙前後底線,使用者名稱字空間的魔法對象或屬性。例如:__init__ , __ 不要自己發明這樣的名字
  • xx_:單後置底線,用於避免與Python關鍵詞的衝突

通過name mangling(名字重整(目的就是以防子類意外重寫基類的方法或者屬性)如:_Class__object)機制就可以訪問private了。

總結
  • 父類中屬性名稱為__名字的,子類不繼承,子類不能訪問
  • 如果在子類中向__名字賦值,那麼會在子類中定義的一個與父類相同名字的屬性
  • _名的變數、函數、類在使用from xxx import *時都不會被匯入

 

二、屬性property

1. 私人屬性添加getter和setter方法
 1 class Money(object): 2     def __init__(self): 3         self.__money = 0 4  5     def getMoney(self): 6         return self.__money 7  8     def setMoney(self, value): 9         if isinstance(value, int):10             self.__money = value11         else:12             print("error:不是整型數字")
2. 使用property升級getter和setter方法
 1 class Money(object): 2     def __init__(self): 3         self.__money = 0 4  5     def getMoney(self): 6         return self.__money 7  8     def setMoney(self, value): 9         if isinstance(value, int):10             self.__money = value11         else:12             print("error:不是整型數字")13     money = property(getMoney, setMoney)

運行結果:

In [1]: from get_set import MoneyIn [2]: In [2]: a = Money()In [3]: In [3]: a.moneyOut[3]: 0In [4]: a.money = 100In [5]: a.moneyOut[5]: 100In [6]: a.getMoney()Out[6]: 100
3. 使用property取代getter和setter方法

@property成為屬性函數,可以對屬性賦值時做必要的檢查,並保證代碼的清晰短小,主要有2個作用

  • 將方法轉換為唯讀
  • 重新實現一個屬性的設定和讀取方法,可做邊界判定
 1 class Money(object): 2     def __init__(self): 3         self.__money = 0 4  5     @property 6     def money(self): 7         return self.__money 8  9     @money.setter10     def money(self, value):11         if isinstance(value, int):12             self.__money = value13         else:14             print("error:不是整型數字")

運行結果:

In [3]: a = Money()In [4]: In [4]: In [4]: a.moneyOut[4]: 0In [5]: a.money = 100In [6]: a.moneyOut[6]: 100

 

Python——私人化 和 屬性property

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.