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?
question from:
https://stackoverflow.com/questions/7255655/how-to-subclass-str-in-python 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…