property() 函数的作用是在新式类中返回属性值
1.语法:
class property([fget[, fset[, fdel[, doc]]]])
2.参数:
fget -- 获取属性值的函数
fset -- 设置属性值的函数
fdel -- 删除属性值函数
doc -- 属性描述信息
3.返回值:返回新式类属性
4.实例:银行卡案例,假设钱是私有属性。
classCard:def __init__(self, card_no):'''初始化方法'''self.card_no=card_no
self.__money =0defset_money(self,money):if money % 100 ==0:
self.__money +=moneyprint("存钱成功!")else:print("不是一百的倍数")defget_money(self):return self.__money
def __str__(self):return "卡号%s,余额%d" % (self.card_no, self.__money)#删除money属性
defdel_money(self):print("----->要删除money")#删除类属性
delCard.money
money= property(get_money, set_money, del_money, "有关余额操作的属性")
c= Card("4559238024925290")print(c)
c.money= 500
print(c.money)print(Card.money.__doc__)#删除
delc.moneyprint(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__的时候会打印出字符串的内容