我已经编写了str(内置)类的以下扩展名,以便执行以下操作:假设通过执行“ Ciao”-“ a”,我得到了字符串“ Ciao”-字符串“ Cio”。这是执行此操作的代码,它可以正常工作:
class my_str(str):
def __sub__(self, other):
p = list(other)
l = ""
for el in self:
if (el in p) == False:
l += el
return my_str(l)
if __name__ == "__main__":
s = my_str("Ciao")
p = my_str("a")
t = s - p
print(t) # 'Cio'
print(s) # 'Ciao'
现在。假设我希望函数__sub__
直接更新对象s
,这样,当我在执行print(s)
之后键入s - p
时,输出将为“ Cio”。如何修改类my_str
?
字符串在Python中是不可变的,这意味着对字符串所做的所有更改都会返回一个新字符串。