class Foo: @property def AAA(self): print(‘get‘) @AAA.setter def AAA(self,val): print(‘set‘,val,sep=‘---‘) @AAA.deleter def AAA(self): print(‘del‘) f1=Foo() f1.AAA #get f1.AAA=‘aaa‘ #set---aaa del f1.AAA #del
class Foo: def get_AAA(self): print(‘get‘) def set_AAA(self,val): print(‘set‘,val,sep=‘---‘) def del_AAA(self): print(‘del‘) AAA=property(get_AAA,set_AAA,del_AAA) f1=Foo() f1.AAA #get f1.AAA=‘aaa‘ #set---aaa del f1.AAA #del
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) # 获取商品价格 80.0 obj.price = 200 # 修改商品原价 print(obj.price) #160.0 del obj.price # 删除商品原价 # print(obj.price)
原文:https://www.cnblogs.com/wuweixiong/p/10638187.html