Python使用property函数定义属性访问方法如果不定义fget会怎么样?

时间:2023-03-09 01:06:56
Python使用property函数定义属性访问方法如果不定义fget会怎么样?

我们知道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 "<pyshell#27>", line 1, in <module>
rect.len
AttributeError: unreadable attribute
>>> rect.len=15
execute setLen
>>>

从以上代码可以看到,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!

博客地址:https://blog.****.net/LaoYuanPython


请大家多多支持,点赞、评论和加关注!谢谢!