polymorphism in python

rashkatsa rashkatsa at wanadoo.fr
Wed Nov 26 01:45:51 CET 2003


Hi all !

I have written a little module called 'polymorph' that allows to call 
different methods of a class that have the same name but that have not 
the same number of arguments. *args are supported. You could find the 
module attached to this message.

As in python, you could not define two method with same name (the second 
one override the first one), i have choosen to design it through private 
prefix '__' (defined method names and called method name are different).
You just have to put the number of args of your method (without the 
'self' one) and use the prefix keyword 'p' (polymorph) or 'pe' (elliptic 
method where last argument is '*args').

now an example:

#=======================================================================
import polymorph

""" You could add polymorphism for your class.
     You just have to inherit polymorph.Polymorph class
     and prefix your methods that have the same name
     but differ from the number of args with the
     following prefix :

         __<x>p__ where x is the number of args of your method
         __<x>pe__ where x is the number of args of your method if you
		  use elliptic argument at the end (*args)

     see below for a little demo class.

     Priority : check if __<x>p__... exists before __<x>pe__... for the
	       same <x>.
"""

class Demo(polymorph.Polymorph):
     def __init__(self):
         PolymorphicClass.__init__(self)
     def __1p__foo(self, first):
         return (first,)
     def __2p__foo(self,first,second):
         return (first,second)
     def __0p__bar(self):
         return ()
     def __1pe__bar(self,*args):
         return [args]
     def __2p__bar(self,first,second):
         return (second,first)

aninstance = Demo()

#print "foo with no parameter : ",aninstance.foo()
print "foo with 1 parameter : ",aninstance.foo(3)
print "foo with 2 parameters : ",aninstance.foo(4,6)
#print "foo with 3 parameters : ",aninstance.foo(4,6,8)
print "bar with 0 parameter : ",aninstance.bar()
print "bar with 1 parameter : ",aninstance.bar(4)
print "bar with 2 parameters : ",aninstance.bar(9,1)
print "bar with 10 parameters : ",aninstance.bar(1,2,3,4,5,6,7,8,9,0)
#=======================================================================

returns :

foo with 1 parameter :  (3,)
foo with 2 parameters :  (4, 6)
bar with 0 parameter :  ()
bar with 1 parameter :  [(4,)]
bar with 2 parameters :  (1, 9)
bar with 10 parameters :  [(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)]

I think that this could help to design classes with lesser 'switch' 
behavior in all-in-one method with *args argument.

Do you find it useful ?

regards,

rashkatsa


-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: polymorph.py
URL: <http://mail.python.org/pipermail/python-list/attachments/20031126/a8eebee8/attachment.ksh>


More information about the Python-list mailing list