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

知识共享许可协议 版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons

我们知道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.csdn.net/LaoYuanPython

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

猜你喜欢

转载自blog.csdn.net/LaoYuanPython/article/details/94642566