property 装饰器的作用
property 装饰器将方法包装成属性,将私有属性公有化,此属性只能被读取。相当于实现get方法的对象
class People:
def __init__(self, identity_number):
self._identity_number = identity_number
@property # 只读
def age(self):
return self._age
@age.setter # 写
def age(self, value):
if not isinstance(value, int):
raise ValueError("age must be an integer!")
if value < 0:
raise ValueError("age must more than 0")
self._age = value
@age.deleter # 删除
def age(self):
del self._age
@property
def get_identity_number(self):
return self._identity_number
#In [22]: p = People(123456)
#In [23]: p.age = 18
# In [24]: p.age
# Out[24]: 18
# In [25]: del p.age
# In [26]: p.age
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-26-3523b116dc0e> in <module>()
----> 1 p.age
<ipython-input-21-de21f31a52ce> in age(self)
5 @property # 只读
6 def age(self):
----> 7 return self._age
8
9 @age.setter # 写
AttributeError: 'People' object has no attribute '_age'
# In [27]: p.age = 18
# In [28]: p.age = 18.6
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-8a03211dcd49> in <module>()
----> 1 p.age = 18.6
<ipython-input-21-de21f31a52ce> in age(self, value)
10 def age(self, value):
11 if not isinstance(value, int):
---> 12 raise ValueError("age must be an integer!")
13 if value < 0:
14 raise ValueError("age must more than 0")
ValueError: age must be an integer!
# In [29]: p.age = '11'
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-29-b6d20eff2848> in <module>()
----> 1 p.age = '11'
<ipython-input-21-de21f31a52ce> in age(self, value)
10 def age(self, value):
11 if not isinstance(value, int):
---> 12 raise ValueError("age must be an integer!")
13 if value < 0:
14 raise ValueError("age must more than 0")
ValueError: age must be an integer!
# In [30]: p.age = -1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-30-47db6d5817ed> in <module>()
----> 1 p.age = -1
<ipython-input-21-de21f31a52ce> in age(self, value)
12 raise ValueError("age must be an integer!")
13 if value < 0:
---> 14 raise ValueError("age must more than 0")
15 self._age = value
16
ValueError: age must more than 0
# In [31]:
会把成员函数x转换为getter,相当于做了x = property(); x = x.getter(x_get)
- @property表示只读。
- 同时有@property和@x.setter表示可读可写。
- 同时有@property和@x.setter和@x.deleter表示可读可写可删除。
参考资料:https://docs.python.org/3/library/functions.html?highlight=property#property