Python property用法是什么,属性定义是怎样
Admin 2022-08-10 群英技术资讯 952 次浏览
关于“Python property用法是什么,属性定义是怎样”的知识有一些人不是很理解,对此小编给大家总结了相关内容,具有一定的参考借鉴价值,而且易于学习与理解,希望能对大家有所帮助,有这个方面学习需要的朋友就继续往下看吧。简单地说就是一个类里面的方法一旦被@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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了Django csrf校验的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
pytho多张图片的无损拼接的实现是怎样的?下文有实例供大家参考,对大家了解操作过程或相关知识有一定的帮助,而且实用性强,希望这篇文章能帮助大家,下面我们一起来了解看看吧。
这篇文章主要weidajia 介绍了python目标检测非极大抑制NMS与Soft-NMS实现过程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
在日常开发中,对数据进行序列化和反序列化是常见的数据操作,Python提供了两个模块方便开发者实现数据的序列化操作,即 json 模块和 pickle 模块。本文就为大家详细讲解这两个模块的使用,需要的可以参考一下
多数情况下,仅仅一个判断条件难以满足我们接下来的操作,通常都是多个条件下执行后面的语句。由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,接下来我们就来看看如何用if语句判断多个条件。
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008