[Tutor] get/set attributes

Kent Johnson kent37 at tds.net
Sun May 25 15:03:07 CEST 2008


On Sun, May 25, 2008 at 6:30 AM, Eric Abrahamsen
<eric at ericabrahamsen.net> wrote:

> What I've got so far handles non-existent attributes fine, but using
> keywords to create attributes isn't working (attributes thus set still
> output an empty string), and I'm not sure why. Here's the class:
>
> class Dummy(object):
>    def __init__(self,**atts):
>        for k,v in atts.items():
>            self.k = v

This creates an attribute named k; it does not create an attribute
whose name is the *value* of k. For that you need setattr:
  setattr(self, k, v)

There is a shortcut that replaces the entire loop:
  self.__dict__.update(atts)

Kent


More information about the Tutor mailing list