Python property用法是什么,属性定义是怎样
Admin 2022-08-10 群英技术资讯 549 次浏览
简单地说就是一个类里面的方法一旦被@property装饰,就可以像调用属性一样地去调用这个方法,它能够简化调用者获取数据的流程,而且不用担心将属性暴露出来,有人对其进行赋值操作(避免使用者的不合理操作)。需要注意的两点是
>>> class Goods(): def __init__(self,unit_price,weight): self.unit_price = unit_price self.weight = weight @property def price(self): return self.unit_price * self.weight >>> lemons = Goods(7,4) >>> >>> lemons.price 28
上面通过调用属性的方式直接调用到 price 方法,property把复杂的处理过程封装到了方法里面去,取值的时候调用相应的方法名即可。
A、装饰器方式
在类的方法上应用@property装饰器,即上面那种方式。
B、类属性方式
创建一个实例对象赋值给类属性
>>> class Lemons(): def __init__(self,unit_price=7): self.unit_price = unit_price def get_unit_price(self): return self.unit_price def set_unit_price(self,new_unit_price): self.unit_price = new_unit_price def del_unit_price(self): del self.unit_price x = property(get_unit_price, set_unit_price, del_unit_price) >>> fruit = Lemons() >>> >>> fruit.x #调用 fruit.x 触发 get_unit_price 7 >>> >>> fruit.x = 9 #调用 fruit.x = 9 触发 set_unit_price >>> >>> fruit.x 9 >>> >>> fruit.unit_price #调用 fruit.unit_price 触发 get_unit_price 9 >>> del fruit.x #调用 del fruit.x 触发 del_unit_price >>> >>> fruit.unit_price Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> l.unit_price AttributeError: 'Lemons' object has no attribute 'unit_price'
property方法可以接收四个参数
>>>class Watermelon(): def __init__(self,price): self._price = price #私有属性,外部无法修改和访问 def get_price(self): return self._price def set_price(self,new_price): if new_price > 0: self._price = new_price else: raise 'error:价格必须大于零'
用property代替getter和setter
>>>class Watermelon(): def __init__(self,price): self._price = price @property #使用@property装饰price方法 def price(self): return self._price @price.setter #使用@property装饰方法,当对price赋值时,调用装饰方法 def price(self,new_price): if new_price > 0: self._price = new_price else: raise 'error:价格必须大于零' >>> watermelon = Watermelon(4) >>> >>> watermelon.price 4 >>> >>> watermelon.price = 7 >>> >>> watermelon.price 7
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
之前小编向大家介绍过complex函数,complex函数可以表示复数数据类型,创建一个值为 real + imag * j 的复数,real为实部,imag为虚部。或者转化一个字符串或数为复数。本文将以两个示例演示用python中complex函数提供的real获取实数部分的过程。
这篇文章主要介绍了python 留一交叉验证的实例代码,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
contour和contourf都是画三维等高线图的,下面这篇文章主要给大家介绍了关于python作图基础操作之plt.contour的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
本文总结了两种方法来导入opencv与numpy包,第一种是直接在Pycharm中导入两个包,第二种是在官网下载相关文件进行配置,感兴趣的小伙伴们可以参考一下
这篇文章主要介绍了Python实现读取HTML表格 pd.read_html(),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008