PythonTip >> 博文 >> python

python - @property and the python property

zihua 2014-01-16 18:01:08 点击: 872 | 收藏


A property combines the ability to pass access to an instance variable through methods like getters and setters and the straightforward access to instance variables through dot notation.
let's see an code. 
class Temperature(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        self._temp_fahr = 0
    @property
    def temp(self):
        return (self._temp_fahr - 32) * 5 / 9

    # what if you want to define a setter property
    @temp.setter
    def temp(self, new_temp):
        self._temp_fahr = new_temp * 9 / 5 + 32

and below is code that demonstrate how to use the @property decorated and the @.setter decorated properties.
import unittest
from Classes.Inheritances.Properties import Temperature

class Test(unittest.TestCase):

    def testProperties(self):
        t = Temperature()
        self.assertEqual(t._temp_fahr, 0, "Test failed")
        self.assertEqual(t.temp, -17.777777777777779, "Test failed")
        t.temp = 34
        self.assertEqual(t._temp_fahr, 93.200000000000003, "Test failed")
        self.assertEqual(t.temp, 34.0)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testProperties']
    unittest.main()

原文链接:http://my.oschina.net/u/854138/blog/90072

作者:zihua | 分类: python | 标签: python | 阅读: 872 | 发布于: 2014-01-16 18时 |
上一篇:django环境搭建
下一篇: django1.3的staticfiles