python 类的属性详解

一,

类的属性:讲方法伪装成一个属性,代码上没有什么提示,只是看上去更合理

使用方法:类方法使用装饰器 @property  @属性名.setter  @属性名.deleter

一个静态属性property本质就是实现了get,set,delete三种方法

class Count:
    def __init__(self,lenth,weight)#传入长,宽两个值
        self.lenth = lenth
        self.weight = weight

    @property
    def area(self): # 计算面积
     # get的时候运行我
     self.s = self.lenth*self.weight
     return self.s
  
    @area.setter
    def area(self,value):
        # set的时候运行我,value接收一个外部的值
        self.s = value

    @area.deleter
    def area(self):
        # delete的时候运行我
     print('deleter被执行了')

 

c = Count(lenth = 5, weight = 10)

print(c.area) #area这时作为属性不加括号

 

如果要修改内部结果 self.s 的值:

c = Count(lenth = 5, weight = 10)

c.area = 10 #这时类内部第二个@area.setter修饰的函数参数value的值为10,然后将值传给self.s,实现内部属性的修改

注意:函数具体要实现什么功能可以随意写,这个地方c.area只是告诉执行者,现在要执行这个函数

 

下面来执行 @area.deleter修饰的函数

del c.area

执行上面这个语句,会打印  ''deleter被执行了'' ,并不会真正删除里面的任何属性,除非在函数内部加入 del self.s

 

如果看不懂,再来一个具体的例子:

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()
obj.price         # 获取商品价格 , 执行@property修饰的函数price
obj.price = 200   # 修改商品原价, 执行@price.setter修饰的函数price
print(obj.price)
del obj.price     # 删除商品原价, 执行@price.deleter修饰的函数price

 

posted @ 2018-07-27 16:04  没熟的油菜  阅读(734)  评论(0)    收藏  举报