Insertin **keywords into a class

Fredrik Lundh fredrik at pythonware.com
Tue Mar 20 14:51:45 EST 2001


C. Porter Bassett wrote:
> Can you please tell me why the following code snippet doesn't update the
> value of radius?

only if you can tell me why you think it should update the
value of radius ;-)

> class myClass:
>    def __init__(self, *arguments, **keywords):
>       self.radius = 0.0

here you set radius to 0.0.

>       for kw in keywords.keys():
>          print kw, ":", keywords[kw]
>          self.kw = keywords[kw]

and here you're attempting to update a non-existent
attribute called "kw".  I assume you get an Attribute-
Error...

>       print "self.radius =", self.radius
>
> b = myClass(radius = 1.0)

maybe you were thinking of the __dict__ dictinary (which
holds instance variables)?  something like this would work:

       for kw in keywords.keys():
          print kw, ":", keywords[kw]
          self.__dict__[kw] = keywords[kw]

or, better:

       for k, v in keywords.items():
          setattr(self, k, v)

or, faster:

            self.__dict__.update(keywords)

or perhaps even:

 class myClass:
    def __init__(self, radius=0.0, *arguments, **keywords):
       self.radius = radius

(but that will of course not work if you really need to pass in
arbitrary attributes...)

Cheers /F





More information about the Python-list mailing list