[Tutor] using **kwargs in __init__() as attributes

Kent Johnson kent37 at tds.net
Mon Oct 1 17:06:23 CEST 2007

János Juhász wrote:
> Dear Tutors,
> I would like to make a new class instance, where
> the intance attributes coming from the kwargs hash.
> class ADUser:
>     def __init__(self, **kwargs):
>         for key in kwargs.keys():
>             self.key = kwargs[k]

This sets the 'key' attribute of self to the value of the keyword. You 
want to use the value of of key as the attribute name. You can do this 
with setattr():

   setattr(self, key, kwargs[k])

You can also update all the kwargs at once with

> It isn't working :(

A more specific description of the problem is often helpful; for best 
results copy and paste the exact error message, including the traceback, 
into your email.


More information about the Tutor mailing list