標籤:%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()函數