How to subclass str in Python

后端 未结 5 2047
离开以前
离开以前 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:34

    I'm kinda horrified by the complexity of the other answers, and so is python standard library. You can use collections.UserString to subclass string and do not mess with proxying str's methods.

    Just subclass it, and add your methods. self.data contains the actual string that is being represented by your object, so you can even implement str-"mutating" methods by reassigning self.data internally.

    An example.

提交回复
热议问题