adding a method to an existing builtin class

TP Tribulations at Paralleles.invalid
Sun Sep 26 18:07:22 CEST 2010


Hi everybody,

Today I have learned a bit of the news of Python 3.0 compared to 2.4 
version.

By the way, I have asked myself if it is possible to add a method to a 
builtin type as 'unicode':

>>> a="foo"
>>> type(a)
<type 'unicode'>
>>> print(dir(a))
['__add__', ..., 'zfill']

For example, I would like to add a "colorize" method to 'unicode' objects. 
Is this possible?
Or am I compelled to derive the unicode builtin as below:

class my_unicode(unicode):
   def __init__( self, unicode_string ):
     super( my_unicode, self ).__init__(  )
   def colorize( self ):
       return "\x1b[93;102m" + self + "\x1b[0m"

my_unicode_string = my_unicode( "coucou" )
print( type( my_unicode_string ) )
print( my_unicode_string.colorize() )
print( my_unicode_string.upper() )

Thanks,

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)



More information about the Python-list mailing list