小甲鱼45讲__setattr__无限递归问题
class R:def __init__(self,width=0,height=0):
self.width=width
self.height=height
def __setattr__(self,name,value):
if name=='square':
self.width=value
self.height=value
else:
self.__dict__=value #之前是self.name=value
我不懂__setattr__产生递归的原理,它是多次调用了自身吗,为什么if语句里的内容不会发生递归呢,它(self.width=value)为什么不是赋值调用自身呢?
程序运行路线图:
假设执行 R().square = 5
↓
self.width=5
↓
self.__setattr__('width', 5)
↓
self.__dict__['width']=5
↓
self.height=5
↓
self.__setattr__('height', 5)
↓
self.__dict__['height']=5
↓
程序结束
zltzlt 发表于 2019-10-3 21:34
程序运行路线图:
假设执行 R().square = 5
↓
谢谢啦! 学习了! 插个眼 zltzlt 发表于 2019-10-3 21:34
程序运行路线图:
假设执行 R().square = 5
↓
你好,我还是不理解。一开始错误的代码中,r1=Rectangle(4,5),__init__方法中对属性self.width赋值4,然后自动调用__setattr__方法,执行__setattr__方法中的else分支self. name=value,即self.width=4,为什么不按你画的这个流程往下赋值,而会发生递归呢?
页:
[1]