zoukankan      html  css  js  c++  java
  • Python 使用@property

    1 背景

    C#中提供了属性Property这个概念,让我们在对私有成员赋值、获取时更加方便,而不用像C++分别定义set*和get*两个函数,在使用时也就像直接使用变量一样

    class C(object):

        def __init__(self):

            self._x = None

        def getx(self):

            return self._x

        def setx(self, value):

              if value > 100:

                    raise Exception("value > 10")

              self._x = value

        def delx(self):

            del self._x

        x = property(getx, setx, delx, "I'm the 'x' property.")

    c1 = C()

    c1.x = 100 

    Traceback (most recent call last):

      File "C:string.bak.py", line 63, in <module>

        c1.x = 100

      File "C:string.bak.py", line 54, in setx

        raise Exception("value > 10")

    Exception: value > 10

    每个变量都要写 var = property(getx, setx, delx, "") 比较麻烦,有没更便捷的办法,使用@property

    2 @property

    class Student(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

     

     

    st = Student()

    st.score = "xxx"

    把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作

    Traceback (most recent call last):

      File "C:string.bak.py", line 63, in <module>

        c1.x = 100

      File "C:string.bak.py", line 54, in setx

        raise Exception("value > 10")

    Exception: value > 10

    setx(self, value):

              if value > 100:

                    raise Exception("value > 10")

              self._x = value

     

        def delx(self):

            del self._x

     

        x = property(getx, setx, delx, "I'm the 'x' property.")

     

    c1 = C()

    c1.x = 100

  • 相关阅读:
    centos yum 安装php7.2
    Linux CentOS完全卸载PHP
    Linux: cp 复制文件、文件夹到文件夹
    CentOS 7 yum安装LAMP,LNMP并搭建WordPress个人博客网站
    cin循环输入控制问题
    有序数组中的二分查找
    二叉查找树中元素的删除操作
    如何生成能在没有安装opencv库及vs2010环境的电脑上运行的exe文件
    冒泡排序算法,选择排序算法,插入排序算法
    使用迭代法穷举1到N位最大的数
  • 原文地址:https://www.cnblogs.com/sysnap/p/6593564.html
Copyright © 2011-2022 走看看