Created
September 24, 2013 19:28
-
-
Save mindflayer/6690008 to your computer and use it in GitHub Desktop.
Create class instance on-the-fly with Python
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 Dog(object): | |
... pass | |
... | |
>>> class Cat(object): | |
... pass | |
... | |
>>> def create_object(class_name): | |
... return getattr(__import__(__name__), class_name)() | |
... | |
>>> dog = create_object('Dog') | |
>>> dog | |
<__main__.Dog object at 0x1d9ac50> | |
>>> cat = create_object('Cat') | |
>>> cat | |
<__main__.Cat object at 0x1d9ab50> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replace name with the name of the module where classes are defined.