Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialize class more efficiently in Python

I have this code in which I initialize a class (Adapter) by the name I get from the request.
It seems to be a bit clumsy, and I’m sure there’s a better/cleaner way of doing it.

from adapters.gofirst_adapter import GoFirstAdapter
from adapters.spicejet_adapter import SpiceJetAdapter
from adapters.airasia_adapter import AirAsiaAdapter

class Adapter():
    def __init__(self, adapter_name):
        if(adapter_name=='goFirst'):
            gofirst_adapter = GoFirstAdapter()
            self.adapter = gofirst_adapter
        if(adapter_name=='spiceJet'):
            spicejet_adapter = SpiceJetAdapter()
            self.adapter = spicejet_adapter
        if(adapter_name=='airAsia'):
            airasia_adapter = AirAsiaAdapter()
            self.adapter = airasia_adapter

What I’m aiming at is to have a list of the adapter names such as:

adapters = ['goFirst', 'spiceJet', 'airAsia']

and create the classes by the list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you.

>Solution :

You can use a dict to map the parameter to the specific class:

from adapters.gofirst_adapter import GoFirstAdapter
from adapters.spicejet_adapter import SpiceJetAdapter
from adapters.airasia_adapter import AirAsiaAdapter

class Adapter():
    adapters = {'goFirst':GoFirstAdapter, 'spiceJet':SpiceJetAdapter, 'airAsia':AirAsiaAdapter}
    def __init__(self, adapter_name):
        self.adapter = self.adapters[adapter_name]()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading