Search code examples
pythonpython-3.xstringinheritancesubclass

Change or override str from subclass method


I had a problem with overriding str inside my inherited class. Is there a way to do something similar?

class Sentence(str):
        
    def input(self, msg):
        """Extend allow to hold one changing object for various strings."""
        self = Sentence(input(msg))

    def simplify(self):
        self = self.lower()
        self.strip()

I want to change mine string contained in that class, for various use. There's a way to do this? Because I tried many things from stack, and no one help me.

There is a explain what I want to do:

In init, I initialize Sentence class:

self.sentence = Sentence("") 

Mainloop, where user can change Sentence:

self.sentence.input("Your input:")

After it I want to simplify string for alghoritm:

self.sentence.simplify()

And that's all, after it I want to use self.sentence like string.


But in both methods:

    def input(self, msg):
        """Extend allow to hold one changing object for various strings."""
        self = Sentence(input(msg))

    def simplify(self):
        self = self.lower()
        self.strip()

String wasn't changed.


Solution

  • Due to the optimizations languages such as Python perform on strings (i.e. they are inmutable so the same string can be reused) I don't think it's a good practice to inherit from str, instead, you could write a class that wraps the string:

    class Sentence:
        def __init__(self, msg: str):
            self.msg = msg
    
        def simplify(self):
            self.msg = self.msg.lower().strip()
    

    This way you can improve your implementation if for example you are changing the string too often and you run into performance problems.