Python如何使用@property @x.setter及@x.deleter
@property可以將python定義的函數(shù)“當(dāng)做”屬性訪問(wèn),從而提供更加友好訪問(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é)果:
60
100
123456
代碼
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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java數(shù)據(jù)結(jié)構(gòu)基礎(chǔ):線性表
這篇文章主要介紹了Java的數(shù)據(jù)解構(gòu)基礎(chǔ),希望對(duì)廣大的程序愛(ài)好者有所幫助,同時(shí)祝大家有一個(gè)好成績(jī),需要的朋友可以參考下,希望能給你帶來(lái)幫助2021-07-07Java DefaultListableBeanFactory接口超詳細(xì)介紹
這篇文章主要介紹了Java DefaultListableBeanFactory接口,DefaultListableBeanFactory是整個(gè)bean加載的核心部分,是Spring注冊(cè)機(jī)加載bean的默認(rèn)實(shí)現(xiàn)2022-11-11SpringBoot動(dòng)態(tài)定時(shí)任務(wù)、動(dòng)態(tài)Bean、動(dòng)態(tài)路由詳解
這篇文章主要介紹了SpringBoot動(dòng)態(tài)定時(shí)任務(wù)、動(dòng)態(tài)Bean、動(dòng)態(tài)路由詳解,之前用過(guò)Spring中的定時(shí)任務(wù),通過(guò)@Scheduled注解就能快速的注冊(cè)一個(gè)定時(shí)任務(wù),但有的時(shí)候,我們業(yè)務(wù)上需要?jiǎng)討B(tài)創(chuàng)建,或者根據(jù)配置文件、數(shù)據(jù)庫(kù)里的配置去創(chuàng)建定時(shí)任務(wù),需要的朋友可以參考下2023-10-10Java通過(guò)Lambda表達(dá)式實(shí)現(xiàn)簡(jiǎn)化代碼
我們?cè)诰帉?xiě)代碼時(shí),常常會(huì)遇到代碼又長(zhǎng)又重復(fù)的情況,就像調(diào)用第3方服務(wù)時(shí),每個(gè)方法都差不多,?寫(xiě)起來(lái)啰嗦,?改起來(lái)麻煩,?還容易改漏,所以本文就來(lái)用Lambda表達(dá)式簡(jiǎn)化一下代碼,希望對(duì)大家有所幫助2023-05-05