Search code examples
pythonclassglobal-variables

Creating a 'reset' method in python to reset an edited string


I am learning about classes and I am messing around with them. I am trying to edit a string and reset it back to its original form. But I can't figure out how to make a 'reset' method. I tried creating a variable called 'original_string' and assigning the perimeter 'string' to it in the init method so I can simply assign self.string to original_string. I also tried creating the 'original_string' variable, outside the class. But in methods, it seems like I can't reach variables that were created outside that method. Any ideas on how to create a 'reset' method?

class Reverse:
    original_string = "Some string that will be edited"

    def __init__(self, string):
        self.string = string
        original_string = string

    def __str__(self):
        return self.string

    def reverseAll(self):
        newString = ""
        for char in self.string:
            newString = char + newString
        self.string = newString

    def reverseOrder(self):
        newString = ""
        for word in self.string.split():
            newString = str(word) + " " + newString
        self.string = newString

    def reset(self):
        #Reset the edited string back to the original
        self.string = original_string

string = Reverse("Trying to edit this string and reset it back to normal.")
print(string)
string.reverseOrder()
string.reverseAll()
string.reset()
print(string)

Solution

  • Just add the selfflag at the end

    In [1]: class Reverse:
        ...:     original_string = "Some string that will be edited"
        ...:
        ...:     def __init__(self, string):
        ...:         self.string = string
        ...:
        ...:
        ...:     def __str__(self):
        ...:         return self.string
        ...:
        ...:     def reverseAll(self):
        ...:         newString = ""
        ...:         for char in self.string:
        ...:             newString = char + newString
        ...:         self.string = newString
        ...:
        ...:     def reverseOrder(self):
        ...:         newString = ""
        ...:         for word in self.string.split():
        ...:             newString = str(word) + " " + newString
        ...:         self.string = newString
        ...:
        ...:     def reset(self):
        ...:         #Reset the edited string back to the original
        ...:         self.string = self.original_string
        ...:
        ...: string = Reverse("Trying to edit this string and reset it back to normal.")
        ...: print(string)
        ...: string.reverseOrder()
        ...: string.reverseAll()
        ...: string.reset()
        ...: print(string)
        ...:
        ...:
    Trying to edit this string and reset it back to normal.
    Some string that will be edited   ```