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.
1234567891011121314151617
classPony(object):def__init__(self,name):self.name=nameself.hp=100defmagic_power(self):# Attack opponent with super powerspassdefheal(self):# Increase hp (health point)passclassSnake(object):# Blah blah same as Ponypass
Let’s write a factory method to make this happen:
1234567891011121314151617181920
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()