jack-zheng
5/4/2018 - 9:24 AM

python, syntax, property

python, syntax, property

@property

@property 感觉上就是 Java 里面的 getter 和 setter 的作用, 存在的意义从各种例子上面看更像是权限控制上面的优化

In [18]: class Person(object):
    ...:     def __init__(self, firstname, lastname):
    ...:         self.firstname = firstname
    ...:         self.lastname = lastname
    ...:     def get_firstname(self):
    ...:         print('first name: %s' % firstname)
    ...:

In [19]: person = Person('xiao', 'ming')

In [21]: person.firstname
Out[21]: 'xiao'

In [22]: person.firstname = 'da'

In [23]: person.firstname
Out[23]: 'da'

上例子中, 我们可以随意的设置对象属性, 在对象的控制上并不是很理想, 我们可以通过 @property 来优化他

In [35]: class Person(object):
    ...:     @property
    ...:     def birth(self):
    ...:         return self._birth
    ...:     @birth.setter
    ...:     def birth(self, value):
    ...:         self._birth = value
    ...:     @property
    ...:     def age(self):
    ...:         return 2018 - self._birth
    ...:
    ...:

In [36]: person = Person()

In [37]: person.birth = 2000

In [38]: person.age
Out[38]: 18

In [39]: person.age = 20
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-39-23de733bd176> in <module>()
----> 1 person.age = 20

AttributeError: can't set attribute

上例中,我们没有给 age setter 的属性, 所以给他赋值的时候会抛 Exception

Source

Good Sample