[Tutor] Dicts and classes

Remco Gerlich scarblac@pino.selwerd.nl
Wed, 13 Mar 2002 14:49:15 +0100


I was surprised to see a whole thread after your post, and no-one had the
simple answer to your questions... use getattr() and setattr(). 

On  0, VanL <van@lindbergs.org> wrote:
> If I understand correctly, a class is more or less a dict with a little 
> special sauce thrown in.

Sort of, yes. That is, a class instance is implemented using a dictionary.

> Thus, can I assign to a class like I would a dict?  Get a list of members?

The class' dict is in its .__dict__, but you don't want to touch that.

Your examples below work fine if you use getattr() and setattr().

I'll snip a bit...

> I have exaggerated here, but you get the idea.
> Is there any way to do this:
> 
> class customer:
>     def __init__(self, info):
>         for k in info.keys(): self.k = info[k]
>     def change(self, name, value):
>         self.name = value
>     def print(self, name):
>         print self.name

Yes, like:

class customer:
   def __init__(self, info):
      for k in info.keys(): setattr(self, k, info[k])
   def change(self, name, value):
      setattr(self, name, value)
   def print(self, name):
      print getattr(self, name)

> and even:
> 
> bob = customer({'name':'Bob', 'lastname':'Jones','phone':'555-1234'})
> for member in bob.keys(): print bob.member

Yes, with:

for member in bob.keys(): print getattr(bob, member)

> or finally:
> print 'Customer: %(name)s %(lastname)s' % bob

Yes, if you add a __getitem__ method to the class:

  def __getitem__(self, name):
     return getattr(self, name)


Instead of all of this, you can of course just store a dictionary in the
class (like self.info) as well. But this sort of thing is very easy in
Python :)

-- 
Remco Gerlich