Select subclass based on parameter

I have a module (db.py) that loads data from different types of databases (sqlite, mysql, etc.), the module contains the db_loader class and subclasses (sqlite_loader, mysql_loader) that inherit it.

The type of database used is in a separate parameter file,

How does the user return the correct object?

ie how can I do:

loader = db.loader()

Am I using a method called loader in the db.py module, or is there a more elegant way that a class can select its own subclass based on a parameter? Is there a standard way to do this?

+4
source share
3 answers

Looks like you want a Factory Pattern . You define a factory method (either in your module, or perhaps in a common parent class for all the objects that it can produce) to which you pass the parameter, and it will return an instance of the correct class. In python, the problem is a bit simpler than perhaps some of the details of the wikipedia article, since your types are dynamic.

 class Animal(object): @staticmethod def get_animal_which_makes_noise(noise): if noise == 'meow': return Cat() elif noise == 'woof': return Dog() class Cat(Animal): ... class Dog(Animal): ... 
+4
source

I would save the name of the subclass in the params file and have a factory method that would instantiate the class with its name:

 class loader(object): @staticmethod def get_loader(name): return globals()[name]() class sqlite_loader(loader): pass class mysql_loader(loader): pass print type(loader.get_loader('sqlite_loader')) print type(loader.get_loader('mysql_loader')) 
+2
source

Save the classes in a dict , create an instance of the correct one according to your parameter:

 db_loaders = dict(sqlite=sqlite_loader, mysql=mysql_loader) loader = db_loaders.get(db_type, default_loader)() 

where db_type is the parameter that you include, and sqlite_loader and mysql_loader are the loader classes.

+2
source

All Articles