Python getattr and setattr example

Here’s me playing with getattr and setattr to give an object dictionary semantics. Now I can go:


w = Wooga()
w.x = 1
w.x
>>> 1
w['x']
>>> 1

Fun!

Notice that the setattr means I can’t say “self.data = dict()” in the __init__ method, because that will just go into setattr, so I have to go after the __dict__ directly.

class Wooga(object):

    def __init__(self):
        self.__dict__['data'] = dict()

    def __getattr__(self, name):
        return self.data.get(name, None)

    def __setattr__(self, name, value):
        self.data[name] = value

    def __getitem__(self, name):
        return self.data.get(name, None)
Advertisements

4 Comments

Filed under python, utility

4 responses to “Python getattr and setattr example

  1. Tarcisio

    I was able to get the same results with this:

    class Foo(object):
    __getitem__ = object.__getattribute__
    __setitem__ = object.__setattr__

    Are there any meaningful differences?

  2. roby2358

    Neat! I don’t know, but yours is a lot smaller. I’ll have to play with it and find out. Thank you!

    • roby2358

      @Tarcisio … EPIC WIN! Here’s where I finally landed. I use “Ob” objects as throw-around objects where I want to play with the attribute/item distinction.

      class Ob(object):
      __getitem__ = object.__getattribute__
      __setitem__ = object.__setattr__

      def __init__(self, **kwargs):
      # see if the passed in initialization values
      if kwargs:
      for key in kwargs.keys():
      self[key] = kwargs[key]

      Thank you dude! ROCK ON!

  3. Pingback: Loosely Connected

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s