UnkwnTech UnkwnTech - 2 months ago 27
Python Question

Extending builtin classes in python

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.

Answer

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