Multiple initialization methods?

xtian wilberforce at gmail.com
Wed Feb 16 22:56:33 EST 2005


Several people have told you about dispatching to the different methods
based on the different parameters. Another technique is to have the
different initialisation methods be static or class methods. For
example, the python dictionary type can be instantiated in a variety of
ways:

dict(a=1, b=2, c=3) -> {'a': 1, 'c': 3, 'b': 2}

dict([('a',1), ('b',2), ('c',3)])  -> {'a': 1, 'c': 3, 'b': 2}

These are examples of dispatching to different initialisers based on
the passed parameters, but there's also the fromkeys() class method,
which accepts a list of keys and will return a new dictionary with the
elements of the list as keys:

dict.fromkeys(['a','b','c']) -> {'a': None, 'c': None, 'b': None}

This could be implemented as follows:

class dict(object):
.   def __init__(self, *args, **kws):
.       # standard initialisation...
.
.   def fromkeys(cls, keys):
.       # transform the list of keys into a list of (key, value) pairs,
.       # then delegate to the standard initialiser
.       return cls([(k, None) for k in keys])
.       # or:
.       result = cls()
.       for k in keys:
.           result[k] = None
.       return result
.   fromkeys = classmethod(fromkeys)

(In 2.4, this could use decorators and generator comprehensions
instead.)

I often use this (even in languages like Java which support
overloading) when instantiating domain objects that might be retrieved
in many different ways, for example getting an instance of a user by
database id or by login details:

u = User.getById(1234)
u = User.getByLogin(username, password)

Cheers,
xtian




More information about the Python-list mailing list