在接觸python時(shí)最開(kāi)始接觸的代碼,取長(zhǎng)方形的長(zhǎng)和寬,定義一個(gè)長(zhǎng)方形類,然后設(shè)置長(zhǎng)方形的長(zhǎng)寬屬性,通過(guò)實(shí)例化的方式調(diào)用長(zhǎng)和寬,像如下代碼一樣。
1
2
3
4
5
6
|
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)重的后果。
1
2
3
4
5
6
7
8
|
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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Rectangle(object): 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)行屬性的修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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)不在贅述。
1
2
3
|
@height.deleter def height(self): del self.true_height |
總結(jié)一下@property提供了可讀可寫可刪除的操作,如果像只讀效果,就只需要定義@property就可以,不定義代表禁止其他操作。
以上這篇python @property的用法及含義全面解析就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/qq_41673534/article/details/79221070