Python中的property()函數


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 = 500
print(c.money)

print(Card.money.__doc__)

#刪除
del c.money
print(c.money)


執行結果:

卡號4559238024925290,余額0
存錢成功!
500
有關余額操作的屬性
----->要刪除money

AttributeError: '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__ 的時候會打印出字符串的內容

  

  

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM