如何解决Python 类 @property RecursionError
我想让 @property
命名为 image
,如果它存在就返回它,否则我做一些事情然后将它分配给一个变量然后返回它。
class MyClass:
def __init__(self,name: str):
self.name = name
@property
def image(self):
if self.image:
return self.image
# Some code
self.image = 'image url'
return self.image
错误信息:
in image
if self.image: return self.image
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
解决方法
您不能单独使用 self.image
,它会调用您正在处理的函数。这是因为通过使用 @property
定义该函数,当您尝试访问属性 myClassObj.image
时,它实际上会通过调用您的函数 image()
来工作。因此,当您在内部访问 self.image
时,这就是发生递归的地方。
TL;DR:不要在 self.image
函数内访问 image
。
将实际图像存储为 self._image
或类似的内容:
class MyClass:
def __init__(self,name: str):
self.name = name
@property
def image(self):
if self._image:
return self._image
# Some code
self._image = 'image url'
return self._image
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。