Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

subclassing - How to subclass str in Python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...