python中的property註解

來源:互聯網
上載者:User

標籤:python   property   註解   

裝飾器(decorator)可以給函數動態加上功能嗎?對於類的方法,裝飾器一樣起作用。Python內建
的 @property 裝飾器就是負責把一個方法變成屬性調用的:

class Student(object):@propertydef score(self):return self._score@score.setterdef 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

@property 的實現比較複雜,我們先考察如何使用。把一個getter方法變成屬性,只需要加上 @property 就可以
了,此時, @property 本身又建立了另一個裝飾器 @score.setter ,負責把一個setter方法變成屬性賦值,於是,我
們就擁有一個可控的屬性操作:

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

 @property ,我們在對執行個體屬性操作的時候,就知道該屬性很可能不是直接暴露的,而是通過gett
er和setter方法來實現的。
還可以定義唯讀屬性,只定義getter方法,不定義setter方法就是一個唯讀屬性:

class Student(object):    @property    def birth(self):        return self._birth    @birth.setter         #設定了set和get方法    def birth(self, value):        self._birth = value    @property            #設定了get方法    def age(self):        return 2014 - self._birthc=Student()c.birth=10;print c.age
D:\chinaUnicom\Chinese\python.exe D:/python/test1/test3.py2004Process finished with exit code 0


本文出自 “matengbing” 部落格,請務必保留此出處http://matengbing.blog.51cto.com/11395502/1905757

python中的property註解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.