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.
views:
628answers:
3
+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
2008-12-09 12:08:35
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
2008-12-09 12:20:59
@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
2008-12-09 12:24:29
@S.Lott - Ruby's open classes and C#'s extension methods come to mind.
orip
2008-12-09 12:40:50
@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
2008-12-09 12:45:34
+2
A:
See also http://stackoverflow.com/questions/192649/can-you-monkey-patch-methods-on-core-types-in-python
sanxiyn
2008-12-09 12:21:08
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?