在执行Python类定义之前修改输入

在执行Python类定义之前修改输入,python,class,Python,Class,我还在学习Python类是如何工作的。以下是我的示例代码: class StringPopped(str): def __init__(self, input): super().__init__() self.output = input[:-1] str1 = StringPopped('Alice') 然后,str1的输出为Alice和str1。输出为Alic。如何使str1与str1.output具有相同的结果 我尝试了\uuuu repr\u

我还在学习Python类是如何工作的。以下是我的示例代码:

class StringPopped(str):
    def __init__(self, input):
        super().__init__()
        self.output = input[:-1]

str1 = StringPopped('Alice')
然后,str1的输出为
Alice
str1。输出为
Alic
。如何使
str1
str1.output
具有相同的结果


我尝试了
\uuuu repr\uuuu
,但这只会更改显示的内容,而不会更改
str1
的实际值。有没有一种方法可以使语句像
self=self.output

字符串是不可变的。我想你必须用,而不是
\uuuu init\uuuu
来解决这个问题:

>>> class StringPopped(str):
...     def __new__(cls, val):
...         return super().__new__(cls, val[:-1])
...     
>>> s = StringPopped('Alice')
>>> s
'Alic'
>>> type(s)
__main__.StringPopped

这看起来根本不像是一个班级的案例。这应该是一个函数,
def(string):返回string[:-1]
。如果您想了解Python类的工作原理,那么从内置类型继承并不是一个有趣的方法。