python特性 property_python 特性 property
1 什么是特性property
property是一種特殊的屬性,訪問它時會執行一段功能(函數)然后返回值
1 import math
2 class Circle:
3 def __init__(self,radius): #圓的半徑radius
4 self.radius=radius
5
6 @property
7 def area(self):
8 return math.pi * self.radius**2 #計算面積
9
10 @property
11 def perimeter(self):
12 return 2*math.pi*self.radius #計算周長
13
14 c=Circle(10)
15 print(c.radius)
16 print(c.area) #可以向訪問數據屬性一樣去訪問area,會觸發一個函數的執行,動態計算出一個值
17 print(c.perimeter) #同上
18 '''
19 輸出結果:
20 314.1592653589793
21 62.83185307179586
22 '''
注意:此時的特性arear和perimeter不能被賦值
c.area=3 #為特性area賦值
'''
拋出異常:
AttributeError: can't set attribute
'''
2 為什么要用property
將一個類的函數定義成特性以后,對象再去使用的時候obj.name,根本無法察覺自己的name是執行了一個函數然后計算出來的,這種特性的使用方式遵循了統一訪問的原則
除此之外,看下
ps:面向對象的封裝有三種方式:
【public】
這種其實就是不封裝,是對外公開的
【protected】
這種封裝方式對外不公開,但對朋友(friend)或者子類(形象的說法是“兒子”,但我不知道為什么大家 不說“女兒”,就像“parent”本來是“父母”的意思,但中文都是叫“父類”)公開
【private】
這種封裝對誰都不公開
python并沒有在語法上把它們三個內建到自己的class機制中,在C++里一般會將所有的所有的數據都設置為私有的,然后提供set和get方法(接口)去設置和獲取,在python中通過property方法可以實現
1 class Foo:
2 def __init__(self,val):
3 self.__NAME=val #將所有的數據屬性都隱藏起來
4
5 @property
6 def name(self):
7 return self.__NAME #obj.name訪問的是self.__NAME(這也是真實值的存放位置)
8
9 @name.setter
10 def name(self,value):
11 if not isinstance(value,str): #在設定值之前進行類型檢查
12 raise TypeError('%s must be str' %value)
13 self.__NAME=value #通過類型檢查后,將值value存放到真實的位置self.__NAME
14
15 @name.deleter
16 def name(self):
17 raise TypeError('Can not delete')
18
19 f=Foo('egon')
20 print(f.name)
21 # f.name=10 #拋出異常'TypeError: 10 must be str'
22 del f.name #拋出異常'TypeError: Can not delete'
1 class Foo:
2 def __init__(self,val):
3 self.__NAME=val #將所有的數據屬性都隱藏起來
4
5 def getname(self):
6 return self.__NAME #obj.name訪問的是self.__NAME(這也是真實值的存放位置)
7
8 def setname(self,value):
9 if not isinstance(value,str): #在設定值之前進行類型檢查
10 raise TypeError('%s must be str' %value)
11 self.__NAME=value #通過類型檢查后,將值value存放到真實的位置self.__NAME
12
13 def delname(self):
14 raise TypeError('Can not delete')
15
16 name=property(getname,setname,delname) #不如裝飾器的方式清晰
17
18 一種property的古老用法
總結
以上是生活随笔為你收集整理的python特性 property_python 特性 property的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .hpp文件_3 OpenCV的头文件说
- 下一篇: python输入多个数据存入列表_pyt