property补充
# class Foo: # @property # def AAA(self): # print('get的时候运行我啊') # # @AAA.setter # def AAA(self,val): # print('set的时候运行我啊',val) # @AAA.deleter # def AAA(self): # print('del的时候运行我啊') # #只有在属性AAA定义property后才能定义AAA.setter,AAA.deleter # f1=Foo() # f1.AAA # f1.AAA='aaa' # del f1.AAA class Foo: def get_AAA(self): print('get的时候运行我啊') def set_AAA(self,val): print('set的时候运行我啊',val) def del_AAA(self): print('del的时候运行我啊') AAA=property(get_AAA,set_AAA,del_AAA) #只有在属性AAA定义property后才能定义AAA.setter,AAA.deleter f1=Foo() f1.AAA f1.AAA='aaa' del f1.AAA
property应用
class Goods: def __init__(self): # 原价 self.original_price = 100 # 折扣 self.discount = 0.8 @property def price(self): # 实际价格 = 原价 * 折扣 new_price = self.original_price * self.discount return new_price @price.setter def price(self, value): self.original_price = value @price.deleter def price(self): del self.original_price obj = Goods() print(obj.price) # 获取商品价格 obj.price = 200 # 修改商品原价 print(obj.price) del obj.price # 删除商品原价 # print(obj.price)