我们知道Python使用property函数定义属性访问方法时的语法如下:
实例属性=property(fget=None, fset=None, fdel=None, doc=None)
而是要@property装饰器也可以实现同样的功能,但@property装饰器要求必须定义getter装饰器来实现属性访问的get方法,而property函数说明文档对此没有要求,只要求fget、fset、fdel有一个有效就可以。那么如果没定义fget会怎么样?我们来看个简单案例:
>>> class Rectangle():
def __init__(self,length,width): self.width,self.__length = width,length
def setLen(self,length):
print("execute setLen")
self.__length=length
def getLen(self):
print("execute getLen")
return self.__length
len = property(None,setLen,None,'长方形的长')
>>> rect=Rectangle(10,5)
>>> rect.len
Traceback (most recent call last):
File "", line 1, in
rect.len
AttributeError: unreadable attribute
>>> rect.len=15
execute setLen
>>>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
从以上代码可以看到,fget可以不设置,但执行属性读取时会报属性不能读取。
相关内容可以参考:
1、《Python使用property函数定义属性简化属性访问的代码实现》
2、《 Python案例详解:使用property函数定义属性简化属性访问代码实现》
3、《Python案例详解:使用property函数定义与实例变量同名的属性会怎样?》
4、《Python案例详解: @property装饰器定义属性访问方法getter、setter、deleter》
5、《Python中的@property装饰器定义属性访问方法getter、setter、deleter 详解》
6、《Python使用property函数和使用@property装饰器定义属性访问方法的异同点分析》
老猿Python,跟老猿学Python!
博客地址:http://iyenn.com/index/link?url=https://blog.csdn.net/LaoYuanPython
请大家多多支持,点赞、评论和加关注!谢谢!
文章知识点与官方知识档案匹配,可进一步学习相关知识
Python入门技能树基础语法函数333581 人正在系统学习中

老猿Python
微信公众号
专注Python相关语言、图像音视频处理、AI


评论记录:
回复评论: