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

第二种方式

class Goods():


    def __init__(self):
        #原价
        self.original_price = 100
        #折扣
        self.discount = 0.8

    def get_price(self):
        #实际价格 = 原价 * 折扣
        new_price = self.original_price * self.discount
        return new_price

    def set_price(self, value):
        self.original_price = value


    def delete_price(self):
        del self.original_price

    PRICE = property(get_price, set_price, delete_price, "价格属性描述")


obj = Goods()
print(obj.PRICE)    #获取商品价格
obj.PRICE = 200     #修改商品价格
print(obj.PRICE)   
del obj.PRICE        #删除商品价格
print(Goods.PRICE.__doc__)

 

posted @ 2019-01-25 18:25  nester_liz  阅读(198)  评论(0编辑  收藏  举报