@property如何在Python中使用-創(chuàng)新互聯(lián)

這篇文章給大家介紹@property如何在Python中使用,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

成都創(chuàng)新互聯(lián)公司為客戶提供專業(yè)的網(wǎng)站制作、成都網(wǎng)站建設、程序、域名、空間一條龍服務,提供基于WEB的系統(tǒng)開發(fā). 服務項目涵蓋了網(wǎng)頁設計、網(wǎng)站程序開發(fā)、WEB系統(tǒng)開發(fā)、微信二次開發(fā)、成都做手機網(wǎng)站等網(wǎng)站方面業(yè)務。
class Student(object):

  def get_score(self):
    return self._score

  def set_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 ~ 100!')
    self._score = value

我們調用的時候需要這么調用:

>>> s = Student()
>>> s.set_score(60) # ok!
>>> s.get_score()
60
>>> s.set_score(9999)
Traceback (most recent call last):
 ...
ValueError: score must between 0 ~ 100!

但是為了方便,節(jié)省時間,我們不想寫s.set_score(9999)啊,直接寫s.score = 9999不是更快么,加了方法做限制不能讓調用的時候變麻煩啊,@property快來幫忙….

class Student(object):

  @property
  def score(self):
    return self._score

  @score.setter #@score.setter是前一個@property裝飾后的副產(chǎn)品。
  def score(self,value):
    if not isinstance(value, int):
      raise ValueError('分數(shù)必須是整數(shù)才行吶')
    if value < 0 or value > 100:
      raise ValueError('分數(shù)必須0-100之間')
    self._score = value

看上面代碼可知,把get方法變?yōu)閷傩灾恍枰由螥property裝飾器即可,此時@property本身又會創(chuàng)建另外一個裝飾器@score.setter,負責把set方法變成給屬性賦值,這么做完后,我們調用起來既可控又方便

>>> s = Student()
>>> s.score = 60 # OK,實際轉化為s.set_score(60)
>>> s.score # OK,實際轉化為s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
 ...
ValueError: score must between 0 ~ 100!

關于@property如何在Python中使用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

本文名稱:@property如何在Python中使用-創(chuàng)新互聯(lián)
文章分享:http://www.muchs.cn/article18/djjjdp.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供電子商務、做網(wǎng)站、企業(yè)網(wǎng)站制作App設計、虛擬主機、微信公眾號

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設公司