Created
January 23, 2014 18:09
-
-
Save asemt/8583717 to your computer and use it in GitHub Desktop.
Dynamically add attributes to a Python object
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 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