首页 > 代码库 > Python 使用@property

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

Python 使用@property