特性工厂函数
def quantity(storage_name):
def qty_getter(instance):
return instance.__dict__[storage_name]
def qty_setter(instance,value):
if value > 0:
instance.__dict__[storage_name] = value
else:
raise ValueError('value must be > 0')
return property(qty_getter, qty_setter)
class LineItem:
weight = quantity('weight') #相当于就是使用了@property装饰器,为weight设置了get和set
price = quantity('price') #相当于就是使用了@property装饰器,为weight设置了get和set
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
if __name__ == '__main__':
item = LineItem("苹果", -1, -5) # 会调用weight和price的set方法
print(item) #报错,weight和price的值必须要大于0
item = LineItem("苹果", 1, 5)
print(item.weight, item.price) # 会调用weight和price的get方法
-------------------------------------------
个性签名:代码过万,键盘敲烂!!!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!