[Tutor] using **kwargs in __init__() as attributes
Noufal Ibrahim
noufal at airtelbroadband.in
Mon Oct 1 20:18:37 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]
>
> a = ADUser(name='papa')
>
Your snippet above will set the attribute "key" to kwargs[k] (it will
overwrite the values for the previous keys so you won't get anywhere).
You need to use setattr to do this since the names of the attributes are
available as strings. Here's an example.
>>> class Foo(object):
... def __init__(self,**d):
... for i in d:
... setattr(self,i,d[i])
...
>>>
>>>
>>> x= Foo(name="Papa")
>>> x.name
'Papa'
>>>
--
~noufal
http://nibrahim.net.in/
More information about the Tutor
mailing list