• 静态属性property


    静态属性property(是通过对象去使用)

    property是一种特殊的属性,访问它时会执行一段功能(函数)然后返回值

    1 . 通过@property修饰过的函数属性,调用的时候无需在加()

    class Foo:
        @property
        def f1(self):
            print("f1")
    
    f = Foo()
    
    f.f1
    

    输出:

    f1
    

    1.BMI指数案例

    成人的BMI数值:
    过轻:低于18.5
    正常:18.5-23.9
    过重:24-27
    肥胖:28-32
    非常肥胖, 高于32
      体质指数(BMI)=体重(kg)÷身高^2(m)
      EX:70kg÷(1.75×1.75)=22.86

    class People:
        def __init__(self,name,weight,height):
            self.name = name
            self.weight = weight
            self.height = height
        @property
        def bmi(self):
            return self.weight/(self.height**2)
    
    p = People("zhangsan",75,1.78)
    print(p.bmi)
    

    输出:

    23.671253629592222
    

    2.通过唯一内部封装的方法对值进行修改@name.setter

    class Foo:
        def __init__(self,x):
            self.__Nane = x
    
        @property
        def name(self):
            return self.__Nane
    
        @name.setter        # 前提 name 这个函数已经被 property 修饰过一次;才能name.setter 
        def name(self,val):
            if not isinstance(val,str):
                raise TypeError            # 触发一个错误 让程序终止
            self.__Nane = val
    
    
    f = Foo("lisi")
    print(f.name)
    f.name = "zhangsan"
    print(f.name)
    

    输出:

    lisi
    zhangsan
    
  • 相关阅读:
    Scala编译环境搭建(mac IDEA)
    Scala初见
    boost spirit使用
    基于OPENCV的图像融合
    C++获取hostname&IP&MAC地址
    httpd启动检查
    react eslint 代码格式补全的插件
    将html页面导出为word
    redux的笔记
    img onerror事件的使用
  • 原文地址:https://www.cnblogs.com/baolin2200/p/7407360.html
Copyright © 2020-2023  润新知