How to subclass str in Python

yasar picture yasar · Aug 31, 2011 · Viewed 20.8k times · Source

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 metaclass, and create my class with that meta, or subclass str directly?

And also, I guess I need to implement __new__() somehow, because, my custom methods will modify my string object, and will return new mystr obj.

My class's methods, should be completely chainable with str methods, and should always return a new my class instance when custom methods modified it. I want to be able to do something like this:

a = mystr("something")
b = a.lower().mycustommethod().myothercustommethod().capitalize()
issubclass(b,mystr) # True

I want to have it all the abilities that a str have. For example, a = mystr("something") then I want to use it like, a.capitalize().mycustommethod().lower()

It is my understanding that, I need to implement __new__(). I think so because, strings methods would probably try to create new str instances. So , if I overwrite __new__(), They supposedly would return my custom str class. However, I don't know how to pass arguments to my custom class's __init__() method in that case. And I guess I would need to use type() in order to create a new instance in __new__() method right?

Answer

sth picture sth · Aug 31, 2011

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.