gah! I hate the new string syntax

Pieter Nagel pieter at nagel.co.za
Fri Mar 16 06:47:19 EST 2001


"Amit Patel" <amitp at Xenon.Stanford.EDU> wrote:
>
> Even if strings were a class, and I could extend it, it is NOT the
> thing to do to add new functionality like capitalize().  Suppose
> strings do not have a capitalize method, and I want to add one.  And
> suppose strings are classes and can be extended.  If I wrote:
>
>   class MyString(string):
>      def capitalize(self):
>         ...
>
>
> then I can only capitalize strings I created!

Of course you can. The technique is to modify the String class itself
at runtime so that it understands new methods. Then all instances
will support that, whether you created them or not.

Suppose this is the String module you have to work with, and you
can't change it:

	class String:
	    def __init__(self, str):
	        self.str = str

	    def __str__(self):
	        return self.str

	globalString = String('foo')

And here is your extenstion:

	class MyString:
	    def capitalize(self):
	        self.str = self.str.capitalize()

	String.__bases__ = String.__bases__ + (MyString,)
	globalString.capitalize()
	print globalString

Note that you can now capitalize the String instance which you did
not create.

-- 
     ,_
     /_)              /| /
    /   i e t e r    / |/ a g e l




More information about the Python-list mailing list