python中的property属性
python中使用property属性有两种方法。使用@property装饰器和使用property()函数。
@property装饰器
@property装饰器就是负责把一个方法变成属性调用的。如下实例就可以通过s.score来获得成绩,并且对score赋值之前做出了数据检查。
class C(object): def __init__(self): self._x = 9988 @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x c=C() print(c.x) c.x=10000 print(c.x) del c.x print(c.x)
Traceback (most recent call last): File "C:/Users/Administrator.SC-201903160419/Desktop/note/exer/1.py", line 122, in <module> print(c.x) File "C:/Users/Administrator.SC-201903160419/Desktop/note/exer/1.py", line 108, in x return self._x AttributeError: 'C' object has no attribute '_x' 9988 10000
property()函数
语法
property([fget[, fset[, fdel[, doc]]]])
参数
- fget -- 获取属性值的函数
- fset -- 设置属性值的函数
- fdel -- 删除属性值函数
- doc -- 属性描述信息
返回值
返回新式类属性。
class C(object): def __init__(self): self._x = 9999 def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") c=C() print(c.x) c.x=10000 print(c.x) del c.x print(c.x)
9999 10000 Traceback (most recent call last): File "C:/Users/Administrator.SC-201903160419/Desktop/note/exer/1.py", line 143, in <module> print(c.x) File "C:/Users/Administrator.SC-201903160419/Desktop/note/exer/1.py", line 129, in getx return self._x AttributeError: 'C' object has no attribute '_x'
如果 c 是 C 的实例化, c.x 将触发 getter,c.x = value 将触发 setter , del c.x 触发 deleter。