Python property用法是什么,属性定义是怎样
Admin 2022-08-10 群英技术资讯 759 次浏览
关于“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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了python中的h5py开源库的使用,本文只是简单的对h5py库的基本创建文件,数据集和读取数据的方式进行介绍,需要的朋友可以参考下
这篇文章给大家分享的是有关python怎样做一个简单的搜索引擎的内容,这也是很多学习python的朋友比较感兴趣的一个内容,因此分享一个实例给大家做个参考,一起跟随小编看看吧。
今天教大家怎么实现Tkinter透明窗体,在上篇文章给大家介绍过透明窗体上绘制小球,今天接着通过实例代码给大家分享python使用tkinter实现透明窗体上绘制随机出现的小球的实例代码,感兴趣的朋友跟随小编一起看看吧
这篇文章主要为大家介绍了Python变量的作用域,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
python中,while循环与for循环是经常使用的循环语句,一直到的到结果才会循环结束。但是,也会有一直循环,无法计算出结果的情况出现,这时我们就要跳出循环。本文介绍使用break跳出for循环的两种方法:1、提前定义一个变量,让其为空字符串;2、使用for…else…实现break跳出嵌套的for循环。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008