属性名 = property(获取, 修改, 删除, 备注)
class Goods(object):
def __init__(self):
self.org_price = 1000 # 价格
self.discount = 0.7 # 折扣
def get_price(self):
val = self.org_price * self.discount
# 返回价格*折扣
return val
def set_price(self, new_val):
# 接收new_val,将价格修改为new_val
self.org_price = new_val
def del_price(self):
# 将折扣修改为1(删掉折扣)
self.discount = 1
price = property(get_price, set_price, del_price, "备注:价格")
g = Goods()
print(g.price) # 获取商品价格
g.price = 2000 # 修改商品价格
print(g.price)
del g.price # 删除商品折扣
print(g.price)
print(Goods.price.__doc__)
# 输出结果:
700.0
1400.0
2000