Musings of a Software Developer.

Python Class Factory

Feb 16th, 2012

Today’s post will be on factory design pattern in Python. You can read more about it in Wiki.
This design pattern allows you to create objects without specifying the exact class of object that will be created. Let’s say, you want to create an object based on a provided string.

Here are some classes. Both of them are pets. We want to dynamically create a pet from one of those classes based on a string.

defcreate_class(pet_class_name):# pet_class_name decides what class will be returnedifpet_class_nameis'pony':classInheritedClass(Pony):# You can add additional methods or attributes if neededpassreturnInheritedClasselifpet_class_nameis'snake':# Or you can return the exact classreturnSnake# Create MyPet from a stringMyPet=create_class('pony')# MyPet is now a subclass of Pony# It inherits everything from Ponydjango=MyPet('django')# Kaboom !!!django.magic_power()