class Quantity: def __init__(self, storage_name): """ :param storage_name: 托管类中实例属性 """ self.storage_name = storage_name # print('我被初始化qq') def __set__(self, instance, value): """ :param instance: 托管类实例 :param value: 托管类实例属性赋值 :return: """ print(self, 1111) if value > 0: instance.__dict__[self.storage_name] = value else: raise ValueError('value must > 0') class LineItem: weight = Quantity('weight') price = Quantity('price') def __init__(self, descriptor, weight, price): """ :param descriptor: 物品描述 :param weight: 物品重量 :param price: 价格 """ self.descriptor = descriptor self.weight = weight self.price = price print('我被初始化ll') def subtotal(self): """ :return: 总价值 """ return self.weight * self.price
python拥有特性,但是这个特性貌似只对类开放,对函数并没有完全开放。
函数如果也想变成特性,就需要property装饰器,通过闭包的形式把闭包内函数设置为类属性
类属性 = property(func)
def quantity(storage_name):
def qty_getter(instance):
print(instance)
return instance.__dict__[storage_name]
def qty_setter(instance, value):
if value > 0:
instance.__dict__[storage_name] = value
else:
raise ValueError('value must > 0')
return property(qty_getter, qty_setter)
"""
def func1():
def func(selfs):
print(selfs.subtotal())
return '感谢'
return func
"""
class LineItem:
weight = quantity('weight')
price = quantity('price')
# auto_mi = func1()
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price