欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2018年02月01日 09:45:29   投稿:jingxian  
下面小編就為大家分享一篇python @property的用法及含義全面解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

在接觸python時(shí)最開始接觸的代碼,取長(zhǎng)方形的長(zhǎng)和寬,定義一個(gè)長(zhǎng)方形類,然后設(shè)置長(zhǎng)方形的長(zhǎng)寬屬性,通過實(shí)例化的方式調(diào)用長(zhǎng)和寬,像如下代碼一樣。

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

此時(shí)輸出結(jié)果為10 20

但是這樣在實(shí)際使用中會(huì)產(chǎn)生一個(gè)嚴(yán)重的問題,__init__ 中定義的屬性是可變的,換句話說,是使用一個(gè)系統(tǒng)的所有開發(fā)人員在知道屬性名的情況下,可以進(jìn)行隨意的更改(盡管可能是在無(wú)意識(shí)的情況下),但這很容易造成嚴(yán)重的后果。

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

以上代碼結(jié)果會(huì)輸出寬1.0,可能是開發(fā)人員不小心點(diǎn)了一個(gè)小數(shù)點(diǎn)上去,但是會(huì)系統(tǒng)的數(shù)據(jù)錯(cuò)誤,并且在一些情況下很難排查。

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

class Rectangle(object):
  @property
  def width(self):
    #變量名不與方法名重復(fù),改為true_width,下同
    return self.true_width

  @property
  def height(self):
    return self.true_height
s = Rectangle()
#與方法名一致
s.width = 1024
s.height = 768
print(s.width,s.height)

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

此時(shí),如果在外部想要給width重新直接賦值就會(huì)報(bào)AttributeError: can't set attribute的錯(cuò)誤,這樣就保證的屬性的安全性。

同樣為了解決對(duì)屬性的操作,提供了封裝方法的方式進(jìn)行屬性的修改

class Rectangle(object):
  @property
  def width(self):
    # 變量名不與方法名重復(fù),改為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_height
s = Rectangle()
# 與方法名一致
s.width = 1024
s.height = 768
print(s.width,s.height)

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

@height.deleter
def height(self):
    del self.true_height

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

以上這篇python @property的用法及含義全面解析就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論