Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
class dict_as_class(dict):
"""Proper replacement for UserDict
Allows a dictionary to be used like a class. Really messy, thrown
together in a few minutes as a quick replacement, will probably
tidy this up later"""
def __setattr__(self, k, v):
if k in self.keys():
self[k] = v
elif not hasattr(self, k):
self[k] = v
raise AttributeError, "Cannot set '%s', cls attribute already exists" % ( k, )
print k, v
def __getattr__(self, k):
if k in self.keys():
return self[k]
raise AttributeError
c = dict_as_class()
c['lol'] = 'hello'
c.lol2 = 'hello2'
c.lol2 = 'hello3'
print c
print c.lol2
c2 = dict_as_class(hello='world') = 'yeah'
c.sub = c2
from pprint import pprint as p
p(c, width=5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment