如何更改字符串对象中的字符串对象?

How can I change the string object inside a string object?

我试图通过继承 str (Unlike the answer to this other question) 来创建一个可变字符串对象。

到目前为止,这是我的代码:

class mstr(str):

    def __new__(self, s):

        self.s = list(s)
        return str.__new__(self, s)

    def __getitem__(self, index):
        return self.s[index]

    def __setitem__(self, index, value):    
        self.s[index] = value

    def __eq__(self, other):
        return ''.join(self.s) == other

    def __ne__(self, other):
        return ''.join(self.s) != other

    def __lt__(self, other):
        return len(self.s) < len(other)

    def __gt__(self, other):
        return len(self.s) > len(other)

    def __le__(self, other):
        return len(self.s) <= len(other)

    def __ge__(self, other):
        return len(self.s) >= len(other)

    def __add__(self, other):
        return ''.join(self.s) + other

    def __mul__(self, other):
        return ''.join(self.s) * other

    def __hash__(self):
        return hash(''.join(self.s))

    def __str__(self):
        return ''.join(self.s)

def main():

    s = mstr("Hello ")
    s[5] = " World!"
    print(s)

if __name__ == '__main__':

    main()

仅仅输出这个例子,很容易被__str__return值给骗了:

Hello World! 

也很容易被__加__的return值所愚弄:

print(s + " Bloody madness!")

输出:

Hello World! Bloody madness!

但是,一旦我们通过 __add __ 的另一个参数传递 mstr 本身,就会揭示不可变的真相,例如:

print(s + s)

输出:

Hello World!Hello 

删除所有额外的方法:

class mstr(str):

    def __new__(self, s):

        self.s = list(s)
        return str.__new__(self, s)

    def __setitem__(self, index, value):    
        self.s[index] = value
        self = ''.join(self.s) # Foolish attepmt.

打印输出只是 "Hello "。

那么,如何更改字符串对象中的字符串对象呢?我的意思是,字符串 actualphysical content 存储在 str 或对象或其他什么?无论那是哪里,我想分配 那里 .

它在 here:

typedef struct {
    PyObject_VAR_HEAD
    long ob_shash;
    int ob_sstate;
    char ob_sval[1]; // This part. (Not actually one char.)

    /* ... */
} PyStringObject;

除非你想直接用ctypes什么的来搞砸内存,否则你是搞不定的。如果你搞砸了,奇怪的事情就会发生,因为字符串子类不放弃数据不可变的假设。