Subclassing str object
Terry Reedy
tjreedy at udel.edu
Wed Aug 31 13:07:48 EDT 2011
On 8/31/2011 7:43 AM, Yaşar Arabacı wrote:
> Hİ,
>
> I originally posted my question to here:
> http://stackoverflow.com/q/7255655/886669 Could you people please look
> at it and enlighten me a little bit? I would appreciate an answer either
> from here or at stackoverflow.
I believe two people already gave my answer. If 'a' is bound to a str()
object, "a.capitalize() will return a standard, unmodified str, not your
custom class, so a.capitalize().mycustommethod() will fail.". If you
reject that enlightenment, there is not much more to say. (And if you
accept it, I am not sure what you still need.)
To put is a different way, if you want to chain together existing string
methods and your new methods, you must start with objects of your new
subclass and wrap every string method that you want to chain.
class mystr(str):
...
def capitalize(s): return mystr(str.capitalize(s))
You ended up doing something like this in your edit #3, except you
perhaps should not have the __init__ method (depending on what 'sozcuk'
is) and you do the wrapping on every call instead of just once and use
the generalized signature *arg,**kwds for every method, which will make
tracebacks much less informative.
--
Terry Jan Reedy
More information about the Python-list
mailing list