python學習-property

來源:互聯網
上載者:User
#!/usr/bin/env python#-*- coding:utf-8 -*-'@property'__author__ = 'hui.qian'class Student(object):    passs = Student()s.age = 1000print s.age'''在實際過程中,年齡肯定不會大於1000歲這說明一個問題,屬性的設定要有判斷檢查,不能隨便定義,所以一般定義屬性都是用set\get方法'''class Student(object):    def set_age(self,age):        if age > 150:            raise ValueError('Shemale!')        elif age<0:            raise ValueError('The noise?')        self.age = age    def get_age(self):        return self.ages1 = Student()#s1.set_age(-1)#s1.set_age(151)s1.set_age(100)print s1.get_age()'''但是有人就想要用s1.age的方式調用(反正不是我)那就要請@property出場啦'''class Student1(object):    @property    def age(self):        return self._age    @age.setter    def age(self,value):        if value > 150:            raise ValueError('Shemale!')        elif value<0:            raise ValueError('The noise?')        else:            self._age = value    '上面的@property一定要先定義,不然不識別age's2 = Student1()s2.age = 99print s2.age#如果沒有setter的話,該屬性就變為唯讀屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.