[Tutor] Java and Python (was: Iterators)

Arthur ajs@ix.netcom.com
Tue, 3 Sep 2002 11:42:17 -0400


> Could. Doesn't mean you should.
> I'm curious because although the ability to have multiple
> constructors(al la Delphi) is something I'd like in  Python,
> overloading of constructors is rarely an issue since in
> Python everything is an object so I can pass in whatever
> I like. Combined with default args its just not an issue
> for me.

> Why can't you just define say 6 or 7 parameters, give them
> defaults and then check the types of the arguments at runtime
> calling out to the rquired init function as appropriate?
>
> class C:
>    def __init__(self,p1=None,p2=None,p3=None,p4=None)
>       if type(p1) == type(1) and type(p2) == type("string") \
>       and type(p3 == type(7) and type(p4) == type(0.5):
>           self.initISIF(p1,p2,p3,p4)
>       elif type(p1) == type("str"):
>           self.initSNNN(p1)
>       etc...
>    def initISIF(anInt,aString,anotherInt,aFloat):
>        pass
>    def initSNNN(aString):
>        pass
>
> Its a bit clunky but works for me... its like what you do
> in C++ when the automatic type promotion system breaks
> the overloading mechanism....

Well, for one thing, I'm trying to come up with something I can consider to
be modular, in that  what I am doing is in a constant state of refactoring
and flux.  Ideally, I add to or amend the list of signature lists, and am
largely home. Also, I am in the land of new style classes, so type testing
doens't seem to be the way - but I guess your point works as well with
issinstance and issubclass.

> However that kind of constructor overloading should be
> used with great care or you wind up with class methods
> that are full of type conditionals:
>
>     def aMethod(self,p1):
>         if self.type = something:
>            #do something stuff
>         elif self.type == somethingelse
>            # do something else
>
> Which is the antithesis of OOP and a maintenance nightmare.
>
> Usiakly the way to deal with class explosions is to define a
> function (or factory class) which takes the parameters in,
> figures out which kind of class you really need and hands
> you a pointer to it:
>
> class ShapeFactory:
>     def __init__(....)
>     def makeInstance(self,p1,p2,p3...):
>        if type(p1) == type(2) and.... blah blah:
>           return Rectangle(p1,p2,p3,p4)
>        elif type.....:
>           return Circle(p1,p2)
>        elif....
>
> And so on.

>
> Users then create a factory and request it to give
> them instances...

Aah,  I've heard talk of "factory functions".  Now I have a clue what we are
talking about.

>
> Of course I may be misunderstanding the issues totally,
> like I said I have no experience of PyGeo...
>

Or more likely, I'm misunderstanding what my options might be.

Thanks for some clues.

Art