I want to have @property
named image
that when if its exist just return it simply otherwise I do some stuff and then assign it to a variable and then return it.
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
Error message:
in image
if self.image: return self.image
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
You can't use self.image
in itself, it will call the function that you are working on. This is because by defining that function with @property
, when you try to access the property myClassObj.image
, it will actually work by calling your function image()
. So when you access self.image
inside, this is where the recursion is occurring.
TL;DR : Don't access self.image
inside the image
function.
Have the actual image stored as self._image
or something like that:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.