How to subclass str in Python

后端 未结 5 2046
离开以前
离开以前 2020-12-24 07:09

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

5条回答
  •  心在旅途
    2020-12-24 07:51

    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.

提交回复
热议问题