0

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?

6
  • 5
    Make it a @property? Commented Feb 3, 2022 at 18:05
  • 1
    Write a method to increment self.i and in that method increment both of them. Commented Feb 3, 2022 at 18:06
  • 2
    Better yet, don't have self.idigit be a member. Have it be a function. You shouldn't have "duplicate" state in your object. Have the state hold the base data, use methods to return stuff derived from that data. Otherwise, it's too easy to have the object's state be inconsistent. Commented Feb 3, 2022 at 18:09
  • Ok, thank you. But the question regards variables in general, not necessarily in a defined function. For example: x = 'D' y = x+'123' There is no way to make y update automatically if x changes? Commented Feb 3, 2022 at 18:22
  • 1
    @Adani7 no, variables never work that way. Variables simply names that refer to objects in a given namespace. Now, two variables can refer to the same object, in which case, any changes to that object will be visible to either variable. But just because you used some object being referenced by some variables in the expression who's result you end up assigning to another variable does not make things automatically "recalculate" Commented Feb 3, 2022 at 18:35

1 Answer 1

1

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


Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.