python @property的用法及含義全面解析,@property全面解析

來源:互聯網
上載者:User

python @property的用法及含義全面解析,@property全面解析

在接觸python時最開始接觸的代碼,取長方形的長和寬,定義一個長方形類,然後設定長方形的長寬屬性,通過執行個體化的方式調用長和寬,像如下代碼一樣。

class Rectangle(object):  def __init__(self):    self.width =10    self.height=20r=Rectangle()print(r.width,r.height)

此時輸出結果為10 20

但是這樣在實際使用中會產生一個嚴重的問題,__init__ 中定義的屬性是可變的,換句話說,是使用一個系統的所有開發人員在知道屬性名稱的情況下,可以進行隨意的更改(儘管可能是在無意識的情況下),但這很容易造成嚴重的後果。

class Rectangle(object):  def __init__(self):    self.width =10    self.height=20r=Rectangle()print(r.width,r.height)r.width=1.0print(r.width,r.height)

以上代碼結果會輸出寬1.0,可能是開發人員不小心點了一個小數點上去,但是會系統的資料錯誤,並且在一些情況下很難排查。

這是生產中很不情願遇到的情況,這時候就考慮能不能將width屬性設定為私人的,其他人不能隨意更改的屬性,如果想要更改只能依照我的方法來修改,@property就起到這種作用(類似於java中的private)

class Rectangle(object):  @property  def width(self):    #變數名不與方法名重複,改為true_width,下同    return self.true_width  @property  def height(self):    return self.true_heights = Rectangle()#與方法名一致s.width = 1024s.height = 768print(s.width,s.height)

(@property使方法像屬性一樣調用,就像是一種特殊的屬性)

此時,如果在外部想要給width重新直接賦值就會報AttributeError: can't set attribute的錯誤,這樣就保證的屬性的安全性。

同樣為瞭解決對屬性的操作,提供了封裝方法的方式進行屬性的修改

class Rectangle(object):  @property  def width(self):    # 變數名不與方法名重複,改為true_width,下同    return self.true_width  @width.setter  def width(self, input_width):    self.true_width = input_width  @property  def height(self):    return self.true_height  @height.setter  #與property定義的方法名要一致  def height(self, input_height):    self.true_height = input_heights = Rectangle()# 與方法名一致s.width = 1024s.height = 768print(s.width,s.height)

此時就可以對“屬性”進行賦值操作,同樣的方法還del,用處是刪除屬性,寫法如下,具體實現不在贅述。

@height.deleterdef height(self):    del self.true_height

總結一下@property提供了可讀可寫可刪除的操作,如果像唯讀效果,就只需要定義@property就可以,不定義代表禁止其他動作。

以上這篇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.