码迷,mamicode.com
首页 > 编程语言 > 详细

Python 使用@property

时间:2017-03-21 12:36:41      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:init   height   size   back   方法   需要   set   span   装饰器   

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

标签:init   height   size   back   方法   需要   set   span   装饰器   

原文地址:http://www.cnblogs.com/sysnap/p/6593564.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!