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

  • 相关阅读:
    mysql----show slave status G 说明
    mysqldump 的方式来搭建master-->slave 的复制架构
    C++----练习--string 从文件中一个一个单词的读直到文件尾
    python 全排列combinations和permutations函数
    什么是restful api
    git知识点
    Hash算法解决冲突的方法
    python之单例设计模式
    Linux常用命令大全
    SQLAlchemy中时间格式化及将时间戳转成对应时间的方法-mysql
  • 原文地址:https://www.cnblogs.com/sysnap/p/6593564.html
Copyright © 2011-2022 走看看