tags:

views:

628

answers:

3

How can I extend a builtin class in python? I would like to add a method to the str class.
I've done some searching but all I'm finding is older posts, I'm hoping someone knows of something newer.

+3  A: 

Just subclass the type

>>> class X(str):
...     def myMethod( self ):
...             return int(self)
...
>>> s=X("Hi Mom")
>>> s.lower()
'hi mom'
>>> s.myMethod()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in myMethod
ValueError: invalid literal for int() with base 10: 'Hi Mom'

>>> z=X("271828")
>>> z.lower()
'271828'
>>> z.myMethod()
271828
S.Lott
I was hoping that I wouldn't have to subclass but after some more research I have come to the conclusion that it is not possible any other way, so I'll accept this answer.
Unkwntech
@Unkwntech: Can't imagine a better way than subclassing. Seriously. Whatever you had in mind (monkeypatching?) never seems to work out as well as a clear, precise, obvious subclass.
S.Lott
@S.Lott - Ruby's open classes and C#'s extension methods come to mind.
orip
@orip: Aware of these. Find monkeypatching in all forms to be a management nightmare -- they effectively prevent reuse by injecting features in obscure ways.
S.Lott
A: 

Consider the following code

class X(str):
    def myMethod( self ):
        return int(self)

x1 = X("Hi Mom");
print type(x1);
x1 = "Hi Mom";
print type(x1);

You see that x1's type is changed to "str" during direct assignment x1 = "Hi Mom";.

Is there a way to retain x1, type and do an assignment?