newbie: constructor question

sismex01 at hebmex.com sismex01 at hebmex.com
Mon Oct 14 12:44:00 EDT 2002


> From: Alexander Eisenhuth [mailto:stacom at stacom-software.de]
> 
> Hallo everybody,
> 
> is it possible to implement multiple constructors with 
> different no. of arguments for one class ?
> 
>   >>> class A:
> 	def __init__(self, a):
> 		self._a = a
> 	def __init__(self,a,b):
> 		self._b = b
> 	def __init__(self,a,b,c):
> 		self._c =c
> 

Urgh... this is, like, *so* C++-ish.

;-)

>   >>>obj = A(12)
> 
> Traceback (most recent call last):
>     File "<pyshell#2>", line 1, in ?
>       obj = A(12)
> TypeError: __init__() takes exactly 4 arguments (2 given)
>   >>>
> 

I'm probly gonna get lambasted by C++ peepl, but what'the'h.
C++ *supposedly* has multiple function dispatch, depending on
the function's signature. The compiler matches the number and
type of arguments to the function, and magically calls the
apropriate one.

Alas, it is but a fiendish LIE!

C++ mangles all code object names depending on their signature,
turning them into intellegibly hideous caricatures of their
logical, pronouncable, thinkable, former selves; all in the
name of pseudo-multimethod-dispatch.

OTOH, Python doesn't do this supposed pseudo-multimethod-dispatch,
so you have to roll your own.  BUT, there's no artificial
restrictions on the types and number or arguments you might
receive, so you can do your own stuff depending on optional
parameters you might define.

So, suppose you have this class:

class MagicalQueue:
  def __init__(self, min, max, init):
    self._min = min
    self._max = max
    self._data = []
    self._data += init # (because it's supposed to be a list)

and you want the extra constructors depending on the number
and type of arguments, right?

Well, for one, min isn't ever going to be less than zero,
so you can make that argument optional.  Max is (probably)
an optional argument also, depending if you want your queue
bounded or not; and initial data is most certainly an optional
argument also.

So, the constructor can be redefined as:

  def __init__(self, min=0, max=None, init=None):
    self._min = min
    self._max = max
    self._data = []
    if init:
      self._data += init

So now, functionally, it's like using multiple initializers,
but actually it's the same making some intelligent decisions
inside.

Cool, eh?

:-)

In other words, you have to design your software *around* this
supposed limitation, which isn't really a limitation; I consider
C++ with all the hoops and loops one has to use much more
limiting.

HTH

-gustavo




More information about the Python-list mailing list