[Tutor] assign all parameters of __init__ to class variables?
Steven D'Aprano
steve at pearwood.info
Wed Nov 2 20:35:37 CET 2011
Alex Hall wrote:
> Hi all,
> I have a class which takes a large number of optional arguments for
> its __init__. Instead of going through every single one and assigning
> it to "self.[name]", is there some quick way to take all the
> parameters of the constructor and assign them all to self.[name] in
> one step?
If your class takes more than, oh, half a dozen parameters, that is
often Nature's way of telling you the class is badly designed and tries
to do Too Many Things.
But if you really need to:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
Add your own error checking :)
Also, the above doesn't work with __slots__.
--
Steven
More information about the Tutor
mailing list