Python中的property()函數

來源:互聯網
上載者:User

標籤:%s   strong   init   one   對象   --   作用   attribute   傳回值   

property() 函數的作用是在新式類中返回屬性值

1.文法: 

class property([fget[, fset[, fdel[, doc]]]])

2.參數:
  • fget -- 擷取屬性值的函數
  • fset -- 設定屬性值的函數
  • fdel -- 刪除屬性值函數
  • doc -- 屬性描述資訊 

3.傳回值:返回新式類屬性

4.執行個體:銀行卡案例,假設錢是私人屬性。

class Card:    def __init__(self, card_no):        ‘‘‘初始化方法‘‘‘        self.card_no = card_no        self.__money = 0    def set_money(self,money):        if money % 100 == 0:            self.__money += money            print("存錢成功!")        else:            print("不是一百的倍數")    def get_money(self):        return self.__money    def __str__(self):        return "卡號%s,餘額%d" % (self.card_no, self.__money)    # 刪除money屬性    def del_money(self):        print("----->要刪除money")        # 刪除類屬性        del Card.money    money = property(get_money, set_money, del_money, "有關餘額操作的屬性")c = Card("4559238024925290")print(c)c.money = 500print(c.money)print(Card.money.__doc__)#刪除del c.moneyprint(c.money)執行結果:卡號4559238024925290,餘額0存錢成功!500有關餘額操作的屬性----->要刪除moneyAttributeError: ‘Card‘ object has no attribute ‘money‘

解析:

  1.get_xxx------> 當類外面 print(對象.money) 的時候會調用get_xxx方法

  2.set_xxx------> 當類外面 對象.money=值 的時候會調用set_xxx方法

  3.del.xxx-------> 當類外面 del 對象.money 的時候會調用del_xxx方法 。執行刪除屬性操作的時候,調用del_xxx方法

  4.“引號裡面是字串內容” ===》 字串中寫該屬性的描述 ,當 類名.屬性名稱.__doc__ 的時候會列印出字串的內容

  

  

 

  

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.