1. 程式人生 > >Python——私有化 和 屬性property

Python——私有化 和 屬性property

避免 使用 getter 命名 size 一個 關鍵詞 man 檢查

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 = value 11 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 = value 11 else: 12 print("error:不是整型數字") 13 money = property(getMoney, setMoney)

運行結果:

In [1]: from get_set import Money

In [2]: 

In [2]: a = Money()

In [3]: 

In [3]: a.money
Out[3]: 0

In [4]: a.money = 100

In [5]: a.money
Out[5]: 100

In [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.setter
10     def money(self, value):
11         if isinstance(value, int):
12             self.__money = value
13         else:
14             print("error:不是整型數字")

運行結果:

In [3]: a = Money()

In [4]: 

In [4]: 

In [4]: a.money
Out[4]: 0

In [5]: a.money = 100

In [6]: a.money
Out[6]: 100

Python——私有化 和 屬性property