how to use more than 1 __init__ constructor in a class ?

Rocco Moretti roccomoretti at hotpop.com
Wed Jun 22 13:34:21 EDT 2005


scott wrote:
> hi people,
> 
> can someone tell me, how to use a class like that* (or "simulate" more 
> than 1 constructor) :
> #--
> class myPointClass:
>   def __init__(self, x=0, y=0):
>     self.x = x
>     self.y = y
>   def __init__(self, x=0, y=0, z=0):
>     self.__init__(self, x, y)
>     self.z = z
> #--
> 

You might try:

#--
class myPointClass:
   def __init__(self, x=0, y=0, z=None):
     self.x = x
     self.y = y
     if z is not None:
     	self.z = z
#--

You could also turn __init__ into a dispatch fuction:

#--
class myPointClass:
   def __init__(self, *args):
     if len(args) <= 2:
       self.__init_two(*args)
     if len(args) == 3:
       self.__init_three(*args)
   def __init_two(self, x=0, y=0):
     self.x = x
     self.y = y
   def __init_three(self, x=0, y=0, z=0):
     self.__init_two(x, y)
     self.z = z
#--

But I would definitely recommend looking at your algorithm to determine 
if there is a better way to do what you want, that doesn't require an 
initilizer with two different signatures.



More information about the Python-list mailing list