overloading constructor in python?
Larry Bates
larry.bates at websafe.com
Mon Apr 3 15:46:26 EDT 2006
lennart at kommunicera.umea.se wrote:
> This is probably a really stupid question, but I cant seem to find a
> satisfying answer by myself so here it goes. In for example java we
> could create a class dummie with several constructors, say one that
> takes an int, and one that takes a String as argument. In python it
> doesnt seem possible to have several __init__ methods ( and I assume if
> we could there would be some problem to determine which __init__ to
> use). So my question is how this is normally solved in python? I dont
> really like the idea of using neither
>
> def __init__(self, o):
> if type(o) is ...
>
> nor subclasses for the baseclass, but I cant think of another way. Any
> thoughts anyone?
>
> Thanx
> /Lennart
>
In python it is called duck typing but you don't need separate
constructors:
def __init__(self, c):
if isinstance(c, int): ...do stuff...
elif isinstance(c, list): ...do stuff...
elif isinstance(c, tuple): ...do stuff...
else:
.
.
.
Remember Python doesn't care what c is and doesn't do
type checking so you can do anything you want.
-Larry Bates
More information about the Python-list
mailing list