求助:Flask应用中ThreadPoolExecutor调用场景下递归深度超出错误
解决Flask应用中"maximum recursion depth exceeded while calling a Python object"错误
嘿,我一眼就看出问题出在你的Product类定义里了!咱们来拆解一下:
错误根源:无限递归的属性访问
你给Product类的每个属性都定义了@property装饰器和对应的setter,但这里有个致命的问题:你的property名称和实例变量名称完全一样。
举个例子,当你写:
@property def title(self): return self.title
当你调用product.title时,这个@property方法会尝试返回self.title——而这又会再次触发这个@property方法,陷入无限递归循环,直到Python的递归深度上限被触发,就抛出了你看到的那个错误。
同理,你的setter方法里:
@title.setter def title(self, title): self.title = title
赋值self.title = title会再次调用这个setter方法,同样导致无限递归。
解决方案
其实你的Product类根本不需要这些自定义的@property和setter——因为你没有在里面做任何额外的逻辑(比如数据校验、转换),直接用默认的属性访问就足够了。
方案1:删掉所有@property和setter(推荐)
修改后的Product类会非常简洁:
class Product: def __init__(self): self.title = None self.price = None self.price_string = None self.asin = None
这样你原来的赋值代码product.title = title、product.price = float(price)都能正常工作,不会有任何递归问题。
方案2:如果确实需要自定义property(比如后续要加逻辑)
那你需要把实例变量的名字改成和property名称不同的,比如在前面加下划线:
class Product: def __init__(self): self._title = None self._price = None self._price_string = None self._asin = None @property def title(self): return self._title @title.setter def title(self, title): # 这里可以加自定义逻辑,比如校验title不为空 self._title = title @property def price(self): return self._price @price.setter def price(self, price): # 比如校验价格是正数 if price < 0: raise ValueError("价格不能为负数") self._price = price # 同理修改asin和price_string的property和setter @property def asin(self): return self._asin @asin.setter def asin(self, asin): self._asin = asin @property def price_string(self): return self._price_string @price_string.setter def price_string(self, price_string): self._price_string = price_string
这样就避免了名称冲突,不会触发无限递归。
验证修改
把Product类修改后,再运行你的线程池代码,递归超限的错误应该就消失了。你原来的ScrapePageFull函数不需要做任何改动,直接使用修改后的Product类即可。
内容的提问来源于stack exchange,提问作者Kadiem Alqazzaz
相关产品推荐
相关产品推荐

