newbie: constructor question

Anton Vredegoor anton at vredegoor.doge.nl
Mon Oct 14 19:08:07 CEST 2002


On Mon, 14 Oct 2002 18:31:04 +0200, Alexander Eisenhuth
<stacom at stacom-software.de> wrote:

>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
>
>  >>>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)
>  >>>
>
>--------------------------------
>That doesn't work. Any suggestions ?

Only the last __init__ is preserved, because the previous definitions
are overridden by the last one.

A possible solution is to use default values:

 >	def __init__(self, a = None, b = None, c = None):

Now if an argument is not provided it is set to None, the "default"
value. This works if one or more arguments are provided in their
respective order. To provide only a specific argument, use a keyword:

 obj = A(b=10)

Note that the first argument "self" which stands for the object itself
is counted as an argument but is filled in automagically.

Anton.




More information about the Python-list mailing list