Skip to content

Instantly share code, notes, and snippets.

@ahopkins
Created March 10, 2018 23:36
Show Gist options
  • Save ahopkins/9505b3445149ada4a6f77595615b7c0b to your computer and use it in GitHub Desktop.
Save ahopkins/9505b3445149ada4a6f77595615b7c0b to your computer and use it in GitHub Desktop.
DictObj
class DictObj(dict):
def __init__(self, **kwargs):
dict.__init__(self, **kwargs)
self.__dict__ = self
obj = DictObj(a=1)
print(obj.a) # 1
print(obj.get('a')) # 1
print(obj) # {'a': 1}
obj.a = 2
print(obj.a) # 2
print(obj.get('a')) # 2
print(obj) # {'a': 2}
obj.b = 3
print(obj.b) # 3
print(obj.get('b')) # 3
print(obj) # {'a': 2, 'b': 3}
obj.update({'c': 4})
print(obj.c) # 4
print(obj.get('c')) # 4
print(obj) # {'a': 2, 'b': 3, 'c': 4}
new_obj = DictObj(**{'foo': 'bar'})
print(new_obj.foo) # bar
print(new_obj.get('foo')) # bar
print(new_obj) # {'foo': 'bar'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment