Python中的@property装饰器作用有两个:
- 一个是动态更新功能
- 一个是定义只读属性
首先是动态更新功能,类内加了@property装饰器的函数具备动态更新功能,类似于一种回调函数,只要函数内涉及的变量有变化,该函数就会执行回调,动态更新。
也是因为这种特性,所以@property修饰的可以理解为一个变量,动态更新的也是这个变量。
举个例子:
class Class(object):
def __init__(self, num):
self.a = num
self.c = 100
@property
def b(self):
self._b = self.a
return self._b
temp = Class(0)
print(temp.a)
print(temp.b)
temp.a = 1
print(temp.a)
print(temp.b)
结果:
0
0
1
1
第二个功能是read only属性,也就是说有@property修饰的属性是不能在类外修改的,它只能通过动态更新修改:
class Class(object):
def __init__(self, num):
self.a = num
self.c = 100
@property
def b(self):
self._b = self.a
return self._b
temp = Class(1)
print(temp.a)
print(temp.b)
temp.b = 5
结果:
1
1
Traceback (most recent call last):
File "/home/zxu/workspace_gitlab/track-framework-1/a.py", line 25, in <module>
temp.b = 5
AttributeError: can't set attribute
此时如果我们想要在类外暴露,就要加@setter修饰器,加入 @setter修饰器后等于有了对外的接口:
class Class(object):
@property
def b(self):
return self._b
@b.setter
def b(self, num):
self._b = num
return 124323
temp = Class()
temp.b = 5
print(temp.b)
结果
5