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.youkuaiyun.com/LaoYuanPython

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

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LaoYuanPython

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值