zoukankan      html  css  js  c++  java
  • python3(二十七)property

    """  """
    __author__ = 'shaozhiqi'
    
    
    # 绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,
    # 但是,没办法检查参数,导致可以把参数随便改
    # 比如想限制student score的范围
    
    class Student(object):
    
        def get_score(self):
            return self._score
    
        def set_score(self, value):
            if not isinstance(value, int):
                raise ValueError('score must be an integer!')
            if value < 0 or value > 100:
                raise ValueError('score must between 0 ~ 100!')
            self._score = value
    
    
    s = Student()
    s.set_score(60)
    print(s.get_score())  # 60
    
    
    # print(s.set_score(1000))  # ValueError: score must between 0 ~ 100!
    
    
    # ---------------------property-------------------------------------
    # 上述方法不太简洁,使用property 修改
    # @property装饰器就是负责把一个方法变成属性调用,默认是只读
    class Student1(object):
    
        @property
        def score(self):
            return self._score
    
        @score.setter
        def score(self, value):
            if not isinstance(value, int):
                raise ValueError('score must be an integer!')
            if value < 0 or value > 100:
                raise ValueError('score must between 0 ~ 100!')
            self._score = value
    
    
    s1 = Student1()
    s1.score = 60
    
    
    # s1.score = 9999999  # ValueError: score must between 0 ~ 100!
    
    
    # 报错说明里面有set 方法的实现,如果直接暴露的属性,就不会报错
    
    # 只读属性-------------------------------------------------------
    class Student(object):
    
        @property
        def birth(self):
            return self._birth
    
        @birth.setter
        def birth(self, value):
            self._birth = value
    
        @property
        def age(self):
            return 2019 - self._birth
    
    
    # birth 是一个可读写属性,而age是一个只读属性
    #  age的值可以根据birth计算
    
    s = Student()
    s.birth = 1990
    print(s.birth)  # 注意如果不赋值直接读 会error
    # s.age=100  # error AttributeError: can't set attribute  property 默认是只读
    print(s.age)  # 29
  • 相关阅读:
    常遇问题及解决
    cs231笔记1
    scikit-learn模型参数保存和多分类策略(one vs one和one vs rest)
    练习1_scikit_learn自带数据集_sklearn和svm
    记一次连不上wifi网的处理
    剑指offer | 从1到n整数中1出现的次数 | 22
    剑指offer | 数组中出现次数超过一半的数字 | 21
    剑指offer | 不用加减乘除做加法 | 20
    剑指offer | 二进制中1的个数 | 19
    剑指offer | 链表中环的入口结点 | 18
  • 原文地址:https://www.cnblogs.com/shaozhiqi/p/11550474.html
Copyright © 2011-2022 走看看