| Store | Cart

OT(Slightly): Thanks to Python.

From: Josiah Carlson <jcar...@nospam.uci.edu>
Fri, 12 Mar 2004 23:17:56 -0800
> def foo(a, b) for (type1, type2):>     print "type 1 & 2"> > def foo(a, b) for (type3, type4):>     print "type 3 & 4"

While I don't like the syntax you give, I do agree that it can be 
useful.  I've gotten used to doing the below, but letting the system 
take care of polymorphism would be convenient.

def foo(a, b):
     if type(a) is type1 and type(b) is type2:
         print "type 1 & 2"
     elif type(a) is type3 and type(b) is type4:
         print "type 3 & 4"
     else:
         raise TypeError("Improper argument types passed: %s %s"\
                         %(type(a),type(b)))

Certainly the above can be streamlined with a wrapper function:

def foo1_2(a,b):
     print "type 1 & 2"

def foo3_4(a,b):
     print "type 3 & 4"

def foo(a,b):
     dct = {(type1, type2):foo1_2,
            (type3, type4):foo3_4}
     return dct[type(a), type(b)](a,b)

Which shows us that manual polymorphism is not that bad.

  - Josiah

Recent Messages in this Thread
Aahz Mar 10, 2004 10:48 pm
David M. Wilson Mar 10, 2004 08:34 pm
Jacek Generowicz Mar 08, 2004 09:24 am
JanC Mar 09, 2004 09:25 pm
Michael Hudson Mar 10, 2004 11:47 am
Jacek Generowicz Mar 10, 2004 03:03 pm
JanC Mar 13, 2004 05:24 am
Josiah Carlson Mar 13, 2004 07:17 am
Ville Vainio Mar 13, 2004 09:08 am
Ville Vainio Mar 13, 2004 09:17 am
Messages in this thread