官网函数使用方法介绍
property() 方法的语法:
class property([fget[, fset[, fdel[, doc]]]])
参数
fget – 获取属性值的函数
fset – 设置属性值的函数
fdel – 删除属性值函数
doc – 属性描述信息
返回值
返回新式类属性。
定义一个可控属性值 x
class C(object):
def __init__(self):
self._x = None
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 的实例化, c.x 将触发 getter,c.x = value 将触发 setter , del c.x 触发 deleter。
在类实例化的过程中,通过定义x调用property()方法
python的@property是python的一种装饰器,是用来修饰方法的。
我们可以使用@property装饰器来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性,可以与所定义的属性配合使用,这样可以防止属性被修改。
使用场景
1.修饰方法,使方法可以像属性一样访问。
class Fun(object):
@property
def method_with_property(self): ##含有@property
return 15
def method_without_property(self): ##不含@property
return 15
fun = Fun()
print(fun.method_with_property) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。
print(fun.method_without_property()) #没有加@property , 必须使用正常的调用方法的形式,即在后面加()
两个都输出为15。
print(fun.method_with_property())#TypeError: 'int' object is not callable,添加@property 后,这个方法就变成了一个属性,如果后面加入了(),那么就是当作函数来调用,而它却不是callable(可调用)的。
2.与所定义的属性配合使用,这样可以防止属性被修改。
由于python进行属性的定义时,没办法设置私有属性,因此要通过@property的方法来进行设置。这样可以隐藏属性名,让用户进行使用的时候无法随意修改。
class Fun(object):
def __init__(self):
self._images = 1
self._labels = 2 #定义属性的名称
@property
def images(self): #方法加入@property后,这个方法相当于一个属性,这个属性可以读取,不能修改。
return self._images
@property
def labels(self):
return self._labels
fun = Fun()
#用户进行属性调用的时候,直接调用images即可,而不用知道属性名_images,因此用户无法更改属性,从而保护了类的属性。