[Tutor] Re: Re: Factory classes (etc)
Magnus Lycka
magnus@thinkware.se
Thu, 05 Sep 2002 16:40:23 +0200
At 08:09 2002-09-04 -0700, Emile van Sebille wrote:
> > Python doesn't let you do method overloading?
>
>Python isn't going to do it for you, but you can.
>
>def test(a,b):
> try: return a*1., b+""
> except:
> try: return a+"", b*1.
> except:
> raise 'invalid args'
In general it's a bad idea to use exceptions for other
things than error handling. They cost a lot of performance.
This might be a better solution (assuming that you don't
use keyword arguments):
def typesAreSame(recievedArgs, expectedArgs):
if len(recievedArgs) !=3D len(expectedArgs):
return 0
for recievedArg, expectedArg in zip(recievedArgs, expectedArgs):
if type(recievedArg) !=3D type(expectedArg):
return 0
return 1
(You might want to extent that a bit to check that instances are
of correct class.)
class X:
def needsOverloading(self, *args):
if typesAreSame(args, (1,1,1)):
self.___threeIntegersMethod(self, *args)
elif typesAreSame(args, ("")):
self.___oneStringMethod(self, *args)
...
else:
raise ValueError, 'Bad parameters: %s' % args
But in most cases where you use overloading or templates in
C++ etc, you just write one method in Python, and that's it! :)
Perhaps you need an extra if-statement in the method, but I
have never missed method overloading in Python during the six
years I used it.
--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se