Last active
December 19, 2015 03:48
-
-
Save foxx/5892222 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
else: | |
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') | |
c2.wtf = '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