@property 前言
>>> class test(object):
... def __init__(self):
... self.__num = 10
... def getNum(self):
... return self.__num
... def setNum(self, value):
... self.__num = value
...
>>> t = test()
>>> t.getNum()
10
>>> t.setNum(20)
>>> t.getNum()
20
你会发现,例子中我们属性只有1个,增加了1对方法,也就是2个方法。我们已经知道,当把属性设置为私有属性时,通过添加对应的方法获取其值,通过添加对应的方法设置值,还可以通过方法做数据的有效性校验、过滤等操作。
那么,如果属性非常多时,我们上面的做法又会显得非常麻烦,这有没有好的解决方案呢?答案是有的。python中给我们提供了一些关键词,专门帮我们解决上面的问题,我们今天就详细学习这些知识。
@property 介绍
@property是Python内置的一种装饰器。(什么是装饰器,暂时可以理解为给函数动态加上功能的一种语法)。@property的内部实现是比较复杂的。现在我们先学会如何使用,等以后有了一定的分析源码的能力,再回过头分析其内部实现。
从今以后,见到@property 第一反应就是:@property专门负责把一个方法变成同名属性的。
是一种进行类或实例属性操作(有效性校验、过滤等操作)的有效,简便的途径。
解释:上面我们用修饰了方法,此时会把方法直接变成同名属性。当我们获取属性的值时,实际上就是调用的此方法。
此时,本身又自动创建了另一个装饰器,负责把一个方法变成属性赋值,即:num的setter方法。于是,修饰的其实是,当我们给赋值时,实际上就是调用的此方法。
property方法实现
>>> class test(object):
... def __init__(self):
... self.__num = 10
... def getNum(self):
... return self.__num
... def setNum(self, value):
... self.__num = value
... num = property(getNum, setNum)
...
>>> t = test()
>>> print(t.num) # 10
10
>>> t.num = 20
>>> print(t.num) # 20
20
关于property方法,我们来看下官方文档:
由文档可得:
- property方法包含四个参数,分别为fget,fset,fdel,doc,分别对应getter方法,setter方法,deleter方法和方法说明。
- property()方法返回一个property属性,如果c是C的实例,那么c.x会调用getter方法,c.x = value会调用setter方法,而del c.x会调用deleter方法。
@property 实现
>>> class test(object):
... def __init__(self):
... self.__num = 10
... @property
... def num(self):
... return self.__num
... @num.setter
... def num(self, value):
... self.__num = value
...
>>> t = test()
>>> t.num
10
>>> t.num = 20
>>> t.num
20
关于@property,官方文档如下:
根据文档可得:
- 我们可以把property()方法当成一个装饰器来使用,使用@property对方法进行装饰。
- 装饰器@property把方法x()转换成了与方法名同名的getter方法,"I’m the ‘x’ property."是property的doc参数。
- 调用方法和property()方法一样
补充:
- @property定义只读属性
- @setter定义可读可写属性
- @deleter定义可读可写可删除属性