I am trying to subclass str object, and add couple of methods to it. My main purpose is to learn how to do it. Where I am stuck is, am I supposed to subclass string in a met
Overwriting __new__() works if you want to modify the string on construction:
class caps(str):
def __new__(cls, content):
return str.__new__(cls, content.upper())
But if you just want to add new methods, you don't even have to touch the constructor:
class text(str):
def duplicate(self):
return text(self + self)
Note that the inherited methods, like for example upper() will still return a normal str, not text.