python3中property使用方法详解
本文实例为大家分享了python3中的property使用方法,供大家参考,具体内容如下
property属性
定义
一个可以使实例方法用起来像实例属性一样的特殊关键字,可以对应于某个方法,通过使用property属性,能够简化调用者在获取数据的流程(使代码更加简明)。
property属性的定义和调用要注意以下几点:
调用时,无需括号,加上就错了;并且仅有一个self参数
实现property属性的两种方式
装饰器
新式类中的属性有三种访问方式,并分别对应了三个被
- @property对应读取
- @方法名.setter修改
- @方法名.deleter删除属性
classGoods: def__init__(self): self.age=18 @property defprice(self):#读取 returnself.age #方法名.setter @price.setter#设置,仅可接收除self外的一个参数 defprice(self,value): self.age=value #方法名.deleter @price.deleter#删除 defprice(self): delself.age ################调用############### obj=Goods()#实例化对象 obj.age#直接获取age属性值 obj.age=123#修改age的值 delobj.age#删除age属性的值
类属性
当使用类属性的方式创建property属性时,property()方法有四个参数
- 第一个参数是方法名,调用对象.属性时自动触发执行方法
- 第二个参数是方法名,调用对象.属性=XXX时自动触发执行方法
- 第三个参数是方法名,调用del对象.属性时自动触发执行方法
- 第四个参数是字符串,调用对象.属性.doc,此参数是该属性的描述信息
classGoods(object): def__init__(self): self.price=100#原价 self.discount=0.8#折扣 defget_price(self): #实际价格=原价*折扣 new_price=self.price*self.discount returnnew_price defset_price(self,value): self.price=value defdel_price(self): delself.price #获取设置删除描述文档 PRICE=property(get_price,set_price,del_price,'价格属性描述...') #使用此方式设置 obj=Goods() obj.PRICE#获取商品价格 obj.PRICE=200#修改商品原价 delobj.PRICE#删除商品原价
使用property取代getter和setter方法
使用@property装饰器改进私有属性的get和set方法
classMoney(object): def__init__(self): self.__money=0 #使用装饰器对money进行装饰,那么会自动添加一个叫money的属性,当调用获取money的值时,调用装饰的方法 @property defmoney(self): returnself.__money #使用装饰器对money进行装饰,当对money设置值时,调用装饰的方法 @money.setter defmoney(self,value): ifisinstance(value,int): self.__money=value else: print("error:不是整型数字") a=Money() a.money=100 print(a.money)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。