adding a method to an existing builtin class

T

TP

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':
['__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)
 
C

Chris Rebert

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

The built-in types' classes are immutable; you can only add/override
their methods via subclassing, like you showed.

Cheers,
Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,690
Latest member
MacGyver

Latest Threads

Top