在接觸python時(shí)最開(kāi)始接觸的代碼熬词,取長(zhǎng)方形的長(zhǎng)和寬,定義一個(gè)長(zhǎng)方形類实蔽,然后設(shè)置長(zhǎng)方形的長(zhǎng)寬屬性荡碾,通過(guò)實(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)重的問(wèn)題,__init__ 中定義的屬性是可變的劳殖,換句話說(shuō)铐尚,是使用一個(gè)系統(tǒng)的所有開(kāi)發(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,可能是開(kāi)發(fā)人員不小心點(diǎn)了一個(gè)小數(shù)點(diǎn)上去矛缨,但是會(huì)系統(tǒng)的數(shù)據(jù)錯(cuò)誤爹脾,并且在一些情況下很難排查。
這是生產(chǎn)中很不情愿遇到的情況箕昭,這時(shí)候就考慮能不能將width屬性設(shè)置為私有的灵妨,其他人不能隨意更改的屬性,如果想要更改只能依照我的方法來(lái)修改落竹,@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,用處是刪除屬性性誉,寫(xiě)法如下窿吩,具體實(shí)現(xiàn)不在贅述
@height.deleter
def?height(self):
????del?self.true_height
總結(jié)一下@property提供了可讀可寫(xiě)可刪除的操作,如果像只讀效果错览,就只需要定義@property就可以纫雁,不定義代表禁止其他操作。
本文轉(zhuǎn)自:https://www.jb51.net/article/134148.htm