zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python使用property函数定义的属性名与其他实例变量重名会怎么样?

Python实例属性变量 函数 定义 其他 Property
2023-09-27 14:26:59 时间

首先如果定义的属性名与该属性对应的操作方法操作的实例对象同名就会触发无穷的递归调用,相关部分请参考《Python案例详解:使用property函数定义与实例变量同名的属性会怎样?》
但如果定义为另一个不同的实例变量名相同的名字呢?我们看案例:

   
>>> 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
   width = property(None,setLen,0,'长方形的长')#属性名与实例变量width同名并且未设置get方法

   
>>> rect=Rectangle(10,5)
execute setLen
>>> rect.width
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    rect.width
AttributeError: unreadable attribute
>>> rect.width=15
execute setLen
>>> 
>>> 

从上述案例可以看出,定义的属性width与实例变量width同名,实际映射到的实例变量是len,在执行属性width的查看时,报属性不能读,而执行属性的赋值时,执行的是setLen方法,相当于width这个原本实例变量完全被覆盖。

相关内容可以参考:
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

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