UnkwnTech UnkwnTech - 1 year ago 278
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 Source

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()
>>> z.myMethod()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download