[Tutor] Overloading + factoring

Corran Webster cwebster@nevada.edu
Sat, 4 Dec 1999 09:13:25 -0800


At 10:39 PM -0300 3/12/99, FFlores wrote:
> William Park <parkw@better.net> wrote:
>
> >     class first:
> > 	def __init__(self):
> > 	    ...
> >
> >     class second(first):	# inherits from the first class
> > 	def __init__(self):	# this overrides the first one.
> > 	    ...
>
> Well, that's another thing! I was referring to C++-like
> overloading (i. e. several definitions of the same method,
> to be tested in order until the parameters fit). But I've
> already been told that's not possible.

Overloading in the C++ sense isn't possible, but it is possible to get the
same functionality with a bit of introspection:

class Rectangle:
    def __init__(self, *args):
        if len(args) == 4:
            self.top, self.left, self.bottom, self.right = args
        elif len(args) == 1 and len(args[0]) == 4:
            self.top, self.left, self.bottom, self.right = args[0]
        else:
            raise TypeError, "incorrect arguments"

This can be used as folows:

>>> x = Rectangle(1,2,3,4)
>>> y = Rectangle((1,2,3,4))
>>> y = Rectangle((1,2))
Traceback (innermost last):
  File "<input>", line 1, in ?
  File "<input>", line 8, in __init__
TypeError: incorrect arguments

Keyword arguments can also be a good way to do what you would do with
overloading in C++.

If you are trying to overload __init__, you may find that what you really
want is a collection of factory functions (or one factory function which
does argument testing as above).

Also _operator_ overloading is strongly supported by Python by the
double-underscored "magic" class methods like "__add__".

> > > And something else, though it's not Python-related:
> > > is there a nice method for factoring numbers, calculating
> > > lcd, gcd, and/or a good library of such functions for rational
> > > numbers?
> >
> > Not to my knowledge.  But, you could probably write one yourself.
>
> Oh yes, I could make a function that gives me the prime numbers
> I need. But I'd become old and die while the interpreter is still
> calculating. :) Thanks anyway.

There's likely a C library out there which you may be able to wrap.

Regards,
Corran