在python中创建"重置"方法来重置编辑的字符串



我正在学习课程,我正在搞乱它们。我正在尝试编辑字符串并将其重置回原始形式。但是我不知道如何进行"重置"方法。我尝试创建一个名为"original_string"的变量,并在 init 方法中为其分配外围"字符串",这样我就可以简单地将 self.string 分配给original_string。我还尝试在类外创建"original_string"变量。但是在方法中,我似乎无法访问在该方法之外创建的变量。关于如何创建"重置"方法的任何想法?

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)

只需在末尾添加 self 标志

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   ```

相关内容

  • 没有找到相关文章

最新更新