码迷,mamicode.com
首页 > 其他好文 > 详细

@property

时间:2017-07-16 11:22:23      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:solution   elf   ret   value   span   self   nbsp   screen   color   

Python内置的@property装饰器就是负责把一个方法变成属性调用的:

 

class Screen(object):
     def isint(self,px):
        if not isinstance(px,int):
             raise ValueError(‘px must be an int‘)
        if px<0 :
             raise ValueError(‘px must be not a negative number‘)
   
     @property
     def width(self):
         return self._width
    
     @width.setter
     def width(self,value):
         self.isint(value)
         self._width=value
        
     @property
     def height(self):
         return self._height
    
     @height.setter
     def height(self,value):
         self.isint(value)
         self._height=value
        
     @property
     def resolution(self):
         return self._width * self._height

 

@property给一个Screen对象加上widthheight属性,以及一个只读属性resolution

 

>>> s=Screen()
>>> s.width=666
>>> s.height=888
>>> print(s.resolution)
591408
>>> print(‘s.width * s.height =%d? ‘ % s.resolution)
s.width * s.height =591408?
>>> print(‘s.width * s.height =%d  ‘ % s.resolution)
s.width * s.height =591408 
>>>

@property

标签:solution   elf   ret   value   span   self   nbsp   screen   color   

原文地址:http://www.cnblogs.com/bang325/p/7183770.html

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