Python如何使用@property @x.setter及@x.deleter
@property可以將python定義的函數(shù)“當(dāng)做”屬性訪(fǎng)問(wèn),從而提供更加友好訪(fǎng)問(wèn)方式,但是有時(shí)候setter/deleter也是需要的。
只有@property表示只讀。 同時(shí)有@property和@x.setter表示可讀可寫(xiě)。 同時(shí)有@property和@x.setter和@x.deleter表示可讀可寫(xiě)可刪除。代碼如下
class student(object): #新式類(lèi) def __init__(self,id): self.__id=id @property #讀 def score(self): return self._score @score.setter #寫(xiě) def score(self,value): if not isinstance(value,int): raise ValueError(’score must be an integer!’) if value<0 or value>100: raise ValueError(’score must between 0 and 100’) self._score=value @property #讀(只能讀,不能寫(xiě)) def get_id(self): return self.__id s=student(’123456’) s.score=60 #寫(xiě) print s.score #讀 #s.score=-2 #ValueError: score must between 0 and 100 #s.score=32.6 #ValueError: score must be an integer! s.score=100 #寫(xiě) print s.score #讀 print s.get_id #讀(只能讀,不可寫(xiě))#s.get_id=456 #只能讀,不可寫(xiě):AttributeError: can’t set attribute
運(yùn)行結(jié)果:
60100123456
代碼
class A(object):#要求繼承object def __init__(self): self.__name=None #下面開(kāi)始定義屬性,3個(gè)函數(shù)的名字要一樣! @property #讀 def name(self): return self.__name @name.setter #寫(xiě) def name(self,value): self.__name=value @name.deleter #刪除 def name(self): del self.__name a=A()print a.name #讀a.name=’python’ #寫(xiě)print a.name #讀del a.name #刪除#print a.name # a.name已經(jīng)被刪除 AttributeError: ’A’ object has no attribute ’_A__name’
結(jié)果
None
python
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python爬蟲(chóng)實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊2. Ajax返回值類(lèi)型與用法實(shí)例分析3. 如何在jsp界面中插入圖片4. 詳解盒子端CSS動(dòng)畫(huà)性能提升5. 使用FormData進(jìn)行Ajax請(qǐng)求上傳文件的實(shí)例代碼6. HTML 絕對(duì)路徑與相對(duì)路徑概念詳細(xì)7. asp批量添加修改刪除操作示例代碼8. .NET6打包部署到Windows Service的全過(guò)程9. 解決ajax請(qǐng)求后臺(tái),有時(shí)收不到返回值的問(wèn)題10. css代碼優(yōu)化的12個(gè)技巧
