OOP Python3.5内置str类扩展

问题描述 投票:2回答:1

我已经编写了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 string python-3.x built-in overriding
1个回答
0
投票

字符串在Python中是不可变的,这意味着对字符串所做的所有更改都会返回一个新字符串。

© www.soinside.com 2019 - 2024. All rights reserved.