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

时间:2023-03-09 01:06:57
Python使用property函数定义的属性名与其他实例变量重名会怎么样?

首先如果定义的属性名与该属性对应的操作方法操作的实例对象同名就会触发无穷的递归调用,相关部分请参考《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.****.net/LaoYuanPython


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