Insertin **keywords into a class

Tim Hochberg tim.hochberg at ieee.org
Tue Mar 20 16:12:58 EST 2001


"C. Porter Bassett" <porter at et.byu.edu> wrote :
> cCan you please tell me why the following code snippet doesn't update the
> value of radius?

Because you are updating self.kw instead. Try:

   setattr(self, kw, keywords[kw])

instead of "self.kw = keywords"

I'll make a bit of attempt to expain this, but no gaurantees that it'll be
helpful. "self.kw = keywords[kw]" in this case is translated into
"setattr(self,  'kw', keywords[kw])". Note the quotes around the first kw.
You don't want that. The way you do it now, sets self.kw is set sucessively
to each value in keywords. You might want to throw a "print self.kw" into
your code after the "self.kw =..." line just to see what I mean.

Incidentally, I think you can accomplish the same things with:

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

But I haven't tried it.

-tim

> class myClass:
>    def __init__(self, *arguments, **keywords):
>       self.radius = 0.0
>       for kw in keywords.keys():
>          print kw, ":", keywords[kw]
>          self.kw = keywords[kw]
>       print "self.radius =", self.radius
>
>
> b = myClass(radius = 1.0)
>
>
> --------------------------------------------------------------------------
> "Pretend like this is a really witty saying." - Anonymous
> --------------------------------------------------------------------------
>
>
>





More information about the Python-list mailing list