Skip to content

Instantly share code, notes, and snippets.

@adrianp
Created January 14, 2012 14:58
Show Gist options
  • Save adrianp/1611722 to your computer and use it in GitHub Desktop.
Save adrianp/1611722 to your computer and use it in GitHub Desktop.
Example of how to dynamically add new attributes to an instance of a class (an object) in Python using setattr()
class MyClass:
def __init__(self, a_number, **kwargs):
self.a_number = a_number
for key, value in kwargs.items(): # adding new attributes
setattr(self, key, value)
if __name__ == "__main__":
MY_OBJECT = MyClass(1, a_string = "Hello world!")
print MY_OBJECT.a_number, MY_OBJECT.a_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment