Created
January 14, 2012 14:58
-
-
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()
This file contains 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 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