zoukankan      html  css  js  c++  java
  • day28 property 装饰器

    方法属性装饰器 
    本质上来说就是将方法的执行括号去掉,这样将一个方法掩饰成了一个变量名字,变成了类似属性的东西
    内置装饰器函数,只在面向对象中使用
     1 from math import pi
     2 class Cricle:
     3     def     __init__(self,r):
     4         self.r = r
     5     @property
     6     def perimeter(self):
     7         return 2*pi*self.r
     8     @property
     9     def area(self):
    10         return pi*self.r**2
    11 
    12 c1 = Cricle(5)
    13 
    14 print(c1.perimeter)            # 伪装成一个变量,变成一个属性
    15 # print(c1.perimeter())        # 之前的实现方式
    16 print(c1.area)
    17 # print(c1.area())


    既然是属性能不能改呢~
      很明显是不能的
     1 class Person:
     2     def __init__(self,name,high,weight):
     3         self.name = name
     4         self.high = high
     5         self.weight = weight
     6     @property
     7     def     bmi(self):
     8         return self.weight / self.high ** 2
     9 suyang = Person("苏阳",1.5,180)
    10 # print(suyang.bmi())    # 原先的调用方式
    11 print(suyang.bmi)    # 80.0
    12 suyang.name = "sb"
    13 # suyang.bmi = 18            # 既然是属性,改改试试?.
    14     # AttributeError: can't set attribute    # 毕竟特么不是属性,本质上是方法啊


    property 的实际用例
      商品打折
        不让用户知道真实的价格只能看到打折后的价格
     1 class Goods:
     2     discount = 0.5                    # 打折力度 5折
     3     def __init__(self,name,price):
     4         self.name = name
     5         self.__price = price        # 我才不会让别人知道我的价格
     6     @property
     7     def price(self):
     8         return self.__price * Goods.discount
     9 
    10 apple = Goods("苏阳",0.5)            
    11 print(apple.price)


    补充:
      修改属性 @ name.setter,将原有的属性进行更改替换
     1 class Person:
     2     def __init__(self,name):
     3         self.__name = name
     4     @property
     5     def name(self):
     6         return self.__name +"sb"
     7     @name.setter                # 一般很难用到,计算出来的值一般是直接用不需要再处理了
     8     def    name(self,new_name):
     9         self.__name = new_name
    10 suyang  =  Person("苏阳")
    11 print(suyang.name)    # 苏阳sb
    12 suyang.name    = "suyang"
    13 print(suyang.name)    # suyangsb

  • 相关阅读:
    ASP.NET在禁用视图状态的情况下仍然使用ViewState对象【转】
    Atcoder Regular Contest 061 D Card Game for Three(组合数学)
    Solution 「CERC 2016」「洛谷 P3684」机棚障碍
    Solution 「CF 599E」Sandy and Nuts
    Solution 「洛谷 P6021」洪水
    Solution 「ARC 058C」「AT 1975」Iroha and Haiku
    Solution 「POI 2011」「洛谷 P3527」METMeteors
    Solution 「CF 1023F」Mobile Phone Network
    Solution 「SP 6779」GSS7
    Solution 「LOCAL」大括号树
  • 原文地址:https://www.cnblogs.com/shijieli/p/9922775.html
Copyright © 2011-2022 走看看