在python中创建“重置”方法以重置已编辑的字符串

时间:2019-01-26 22:31:10

标签: python class global-variables

我正在学习课程,并且正在和他们搞混。我正在尝试编辑一个字符串并将其重置回其原始形式。但是我不知道如何进行“重置”方法。我尝试创建一个名为“ original_string”的变量,并在init方法中为其分配边界“ string”,以便我可以简单地将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)

1 个答案:

答案 0 :(得分:0)

只需在末尾添加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   ```