python - How can I change the string object inside a string object? -
i'm trying create mutable string object subclassing str (unlike answer other question).
here's code far:
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()
by outputting example, it's easy fooled __ str __ return value:
hello world!
it's easy fooled return value of __ add __ :
print(s + " bloody madness!")
output:
hello world! bloody madness!
but immutable truth revealed once pass mstr other argument of __ add __, example:
print(s + s)
output:
hello world!hello
removing methods:
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.
output of print(s) "hello ".
so, how can change string object inside string object? mean, string actual , physical content stored in str or object or whatever? wherever is, want assign there.
it's in here:
typedef struct { pyobject_var_head long ob_shash; int ob_sstate; char ob_sval[1]; // part. (not 1 char.) /* ... */ } pystringobject;
unless want screw memory directly ctypes or something, can't @ it. if do screw it, weird things break, because assumption that data immutable isn't waived string subclasses.
Comments
Post a Comment