I have the following code:
class StringIterator:
def __init__(self, compressedString: str):
self.compressedString = compressedString
self.i = 0
self.idigit = self.i +2
The problem is that the variable ‘self.idigit’ (linked to self.i) will not update if self.i changes. For example, if I increment self.i with 1 (self.i += 1), printing or returning self.idigit will not recalculate the variable (returning 1+2=3). How can I do that?
>Solution :
you can read more about property.
class StringIterator:
def __init__(self, compressedString: str):
self.compressedString = compressedString
self.i = 0
# self.idigit = self.i +2 # it is equal is self.idigit = 0 + 2
# you can have a property like this
@property
def idigit(self):
return self.i + 2
obj = StringIterator("Hello")
print(obj.i, obj.idigit) # 0, 2
obj.i += 1
print(obj.i, obj.idigit) # 1,3