Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update a variable linked to another variable in Python

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading