Skip to content

Instantly share code, notes, and snippets.

@mindflayer
Created September 24, 2013 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindflayer/6690008 to your computer and use it in GitHub Desktop.
Save mindflayer/6690008 to your computer and use it in GitHub Desktop.
Create class instance on-the-fly with Python
>>> 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>
@mindflayer
Copy link
Author

Replace name with the name of the module where classes are defined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment