Main Content

Using a Python dictionary as a holder of object attributes

Archive - Originally posted on "The Horse's Mouth" - 2005-04-30 14:09:07 - Graham Ellis

Have a great bank holiday, folks. For any sad (or happy) Python programmers out there, here's a simple example of __getattr__ in use. I've got an object of type thingy with all its atributes held in a dictionary, but I wanted to access them as if each was a separate attribute. "I couldn't find a simple example elsewhere, so I wrote one"


"""Using a dictionary as an attribute handler in Python"""

class thingy:
def __init__(self,indict):
self.stuff = indict
def __getattr__(self,which):
return self.stuff.get(which,None)

about = {"colour":"blue", "type":"flipchart marker"}

markerpen = thingy(about)

print markerpen.colour
print markerpen.age


Further examples at our module pages or learn more with us on our Python course