python @property的介紹與使用

python的@property是python的一種裝飾器,是用來修飾方法的。
1.修飾方法,是方法可以像屬性一樣訪問

class DataSet(object):
  @property
  def method_with_property(self): ##含有@property
      return 15
  def method_without_property(self): ##不含@property
      return 15

l = DataSet()
print(l.method_with_property) # 加了@property後,可以用調用屬性的形式來調用方法,後面不需要加()。
print(l.method_without_property())  #沒有加@property , 必須使用正常的調用方法的形式,即在後面加()

使用 @property 修飾了 method_with_property() 方法,這樣就使得該方法變成了 method_with_property 屬性的 getter 方法。需要注意的是,如果類中只包含該方法,那麼 method_with_property 屬性將是一個只讀屬性。

也就是說,在使用 DataSet 類時,無法對 method_with_property 屬性重新賦值,運行代碼會報錯:

    class Rect:
        def __init__(self,area):
            self.__area = area
        @property
        def area(self):
            return self.__area
        @area.setter
    	def area(self, value):
       		self.__area = value
    rect = Rect(30)
    #直接通過方法名來訪問 area 方法
    print("矩形的面積是:",rect.area)
    

想實現修改 area 屬性的值,還需要爲 area 屬性添加 setter 方法,就需要用到 setter 裝飾器,它的語法格式如下

@方法名.setter
def 方法名(self, value):
    代碼塊
@area.setter
def area(self, value):
	self.__area = value

在運行修改參數時,不會報錯。

    rect.area = 90
    print("修改後的面積:",rect.area)

2.與所定義的屬性配合使用,這樣可以防止屬性被修改。

由於python進行屬性的定義時,沒辦法設置私有屬性,因此要通過@property的方法來進行設置。這樣可以隱藏屬性名,讓用戶進行使用的時候無法隨意修改。

class DataSet(object):
    def __init__(self):
        self._images = 1
        self._labels = 2 #定義屬性的名稱
    @property
    def images(self): #方法加入@property後,這個方法相當於一個屬性,這個屬性可以讓用戶進行使用,而且用戶有沒辦法隨意修改。
        return self._images 
    @property
    def labels(self):
        return self._labels
l = DataSet()
#用戶進行屬性調用的時候,直接調用images即可,而不用知道屬性名_images,因此用戶無法更改屬性,從而保護了類的屬性。
print(l.images) # 加了@property後,可以用調用屬性的形式來調用方法,後面不需要加()。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章