本文摘自php中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于Python描述符的用法介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。作为一位python的使用者,你可能使用python有一段时间了,但是对于python中的描述符却未必使用过,接下来是对描述符使用的介绍
场景介绍
为了引入描述符的使用,我们先设计一个非常简单的类:
1 2 3 4 5 6 | class Product():
def __init__(self,name,quantity,price):
self.name = name
self.quantity = quantity
self.price = price
|
这是一个商品类,存储该商品的名称,数量与价格。
对于一件商品,我们一般会期望它的数量和价格不会是负值,为了避免这种情况,我们可以在初始化的时候加一些判断,比如下面这样:
1 2 3 4 5 6 7 8 9 10 | class Product():
def __init__(self,name,quantity,price):
self.name = name
if quantity<0:
raise ValueError( 'quantity must be >= 0' )
self.quantity = quantity
if quantity<0:
raise ValueError( 'price must be >= 0' )
self.price = price
|
但是这样还会有一个弊端就是这样的判断只是加在了初始化的时候,然后在之后对类的实例的属性进行赋值的时候还是无法保证赋的值是大于0 的
于是我们可以使用‘特性’来解决这个问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class Product():
def __init__(self,name,quantity,price):
self.name = name
self.quantity = quantity
self.price = price
@property
def quantity(self):
return self._quantity
@quantity.setter
def quantity(self,value):
if value < 0:
raise ValueError( 'quantity must be >= 0' )
else :
self._quantity = value
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError( 'price must be >= 0' )
else :
self._price = value
book = Product( 'mybook' ,6,30)
print (book.quantity)
|
这里的@property和@quantity.setter是两个装饰器,它可以设置属性的读与写,就相当于读写属性,但其实是执行一个函数,具体有关特性的介绍,可以再自行查找,这里主要是为了引出描述符。
阅读剩余部分
相关阅读 >>
Python运算符优先级顺序是什么?
Python shell是什么
Python eval的常见错误封装及利用原理的介绍
Python使用当前时间、随机数产生唯一数的方法讲解
Python脚本生成caffe train_list.txt的方法
Python标准库需要导入吗
Python用什么编译器
Python打开py文件一闪而过怎么办?
Python字符串格式化什么意思
Python中找出numpy array数组的最值及其索引方法
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python描述符的用法介绍(附示例)