python property()函数

描述

property() 函数的作用是在新式类中返回属性值。大概意思就是让方法变成一个属性

语法

以下是 property() 方法的语法:

class property([fget[, fset[, fdel[, doc]]]])

参数

  • fget -- 获取属性值的函数
  • fset -- 设置属性值的函数
  • fdel -- 删除属性值函数
  • doc -- 属性描述信息

返回值

返回新式类属性。

实例

 1 #! /usr/bin/python3
 2 # -*- coding:UTF-8 -*-
 3 
 4 class A(object):
 5     def __init__(self):
 6         self._score = None
 7     
 8     def get_score(self):
 9         return self._score
10   
11     def set_score(self, value):
12         self._score = value
13     def del_score(self):
14         del self._score
15     score = property(get_score, set_score, del_score, "I'm the 'score' property")
1 a = A()
2 print(a.score) # a.score将触发getter
3 a.score = 60 #, a.score = 60将触发setter
4 print(a.score)
5 del a.score #将触发deleter
6 # print(a.score) #报错

将 property 函数用作装饰器可以很方便的创建只读属性:

1 class Parrot(object):
2     def __init__(self):
3         self._voltage = 100000
4  
5     @property
6     def voltage(self):
7         """Get the current voltage."""
8         return self._voltage

注:上面的代码将 voltage() 方法转化成同名只读属性的 getter 方法。这里直接不能像上面那个例子,实例化之后修改voltage的值,会报错。

property 的 getter,setter 和 deleter 方法同样可以用作装饰器:

 1 #! /usr/bin/python3
 2 # -*- coding:UTF-8 -*-
 3 
 4 class A(object):
 5     def __init__(self):
 6         self._score = None
 7     
 8     @property
 9     def score(self):
10         return self._score
11     @score.setter
12     def score(self, value):
13         self._score = value
14     @score.deleter
15     def score(self):
16         del self._score

注:这个代码和第一个例子完全相同,但要注意这些额外函数的名字和 property 下的一样,例如这里的 score。


相关链接:

1、https://www.runoob.com/python/python-func-property.html

2、https://www.jianshu.com/p/bfbea5f74ab5

3、https://www.cnblogs.com/miqi1992/p/8343234.html

原文地址:https://www.cnblogs.com/qinduanyinghua/p/13936783.html