need help reseting a class instance

Question:

I’m trying to have my use(self) method change my self.text into an empty str, then have my method reset(self) reset the self.text, but i dont know how to make it so they can both stay as self.text because i need to check for whether or not its a empty string or not later on.

i’m new to this any help is very much appreciated

class WordSlice:
    
    def __init__(self, text: str):
        self.text = text

    def use(self):
        self.text = ''
        return self.text
    
    def reset(self):
        self.text.replace('', self.text)
        return self.text # i see this is the issue but idk how to fix it
Asked By: need help

||

Answers:

As long as I understand you want to restore the text so it should be stored all the time. But you can control access to the text with a boolean flag. If it is not restored (if set to False), the code which uses your class will only be able to get the empty string. Otherwise it will get the actual text.

class WordSlice:
    
    def __init__(self, text: str):
        self.__text = text
        self.restored = True

    @property                  # <-- this will allow you to have a function which
    def text():                #     is called as a property, without brackets
        if not self.restored:
            return ''
        return self.__text

    def use(self):
        self.restored = False
        return ''
    
    def reset(self):
        self.restored = True
        return self.__text

Extra notes:

  1. Strings are immutable. you cannot change them. You can reassign the variable with a new string.

  2. s.replace(x, y) will not mutate your string. It will return a new string with every occurrence of substring x in s replaced with string y.

  3. self.text = self.text.replace(x, y) is the code you should use if you want to actually update the value.

  4. s.replace('', x) will return x if s is empty, otherwise will return s

  5. When you say:

x = "abc"
x = ''

The string "abc" will "dissapear" i.e. will not be accessable in your program and will eventually be cleared from memory by garbage collector.

I hope that helps

Answered By: Andrey Kachow
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.