Multiple constructors

Leif K-Brooks eurleif at ecritters.biz
Sun Feb 6 03:07:43 EST 2005


Philip Smith wrote:
> I don't seem to be able to define multiple versions of __init__ in my matrix 
> class (ie to initialise either from a list of values or from 2 dimensions 
> (rows/columns)).

You could either use an if statement with *args:

class Matrix(object):
     def __init__(self, *args):
         if len(args) == 1:
             # Initialize from list of values
         elif len(args) == 2:
             # Initialize from rows/columns
         else:
             raise TypeError("Constructor accepts 1 or 2 arguments.")

Or with two different functions:

class Matrix(object):
     def __init__(self, values):
         # Initialize from a list of values

     @classmethod
     def from_pair(self, rows, columns):
         return Matrix([rows, columns]) # Or with the right argument



More information about the Python-list mailing list