Skip to content

Instantly share code, notes, and snippets.

@asemt
Created January 23, 2014 18:09
Show Gist options
  • Save asemt/8583717 to your computer and use it in GitHub Desktop.
Save asemt/8583717 to your computer and use it in GitHub Desktop.
Dynamically add attributes to a Python object
class c(object):
def __init__(self, a, b):
self.a = a
self.b = b
def update(self, update_dict):
self.__dict__.update(update_dict)
c = c(1, 2)
c.a
Out[18]: 1
c.b
Out[19]: 2
c.c
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-20-6adf66d1c93d> in <module>()
----> 1 c.c
AttributeError: 'c' object has no attribute 'c'
c.update({'c': 3})
c.c
Out[22]: 3
c.c = 'c'
c.c
Out[24]: 'c'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment