Multiple constructors
vincent wehren
vincent at visualtrans.de
Sun Feb 6 03:25:37 EST 2005
Philip Smith wrote:
> Call this a C++ programmers hang-up if you like.
>
> 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)).
>
> Even if Python couldn't resolve the __init__ to use on the basis of argument
> types surely it could do so on the basis of argument numbers???
>
> At any rate - any suggestions how I code this????
Checking the number of arguments ain't all that hard:
class Klass:
def __init__(*args):
self.args = args
if len(self.args) == 1:
# etc.
This feels rather unpythonic, though. Maybe you could use factory
functions, forgetting about __init__ all together (2.2 or higher):
class Klass(object):
def fromList(seq):
result = Klass()
# populate attributes here
# and return the requested object
return result
fromList = staticmethod(fromList)
def fromDimensions(cols, rows):
result = Klass()
# populate attributes here
# and return the requested object
return result
fromDimensions = staticmethod(fromDimensions)
#more methods here
k = Klass.fromList(seq)
etc..
Regards
--
Vincent Wehren
>
> Thanks
>
> Phil
>
>
More information about the Python-list
mailing list