Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutable str class extension

I've written the following extension of the class str (built-in) in order to do the following operation: Suppose I have the string "Ciao", by doing "Ciao" - "a" I want as a result the string "Cio". Here it is the code that do this and it works fine:

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'

Now, suppose that I'd like the function __sub__ to directly update the object s, in such a way that when I type print(s) after having execute s - p the output would be "Cio". How do I have to modify the class my_str?

like image 961
Matteo Avatar asked Sep 17 '26 14:09

Matteo


1 Answers

You can use

from collections import UserString  
class Test(UserString):
    def __add__(self, other):
        self.data = self.data + other

The UserString class is meant for subclassing the built-in string, and gives you the actual content as a self.data field.

like image 144
blue_note Avatar answered Sep 20 '26 02:09

blue_note



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!