mercredi 1 août 2018

Avoid if else to instantiate a class - python

I want to create an object of a class based on value of a field.

For eg:

if r_type == 'abc':
                return Abc()
            elif r_type == 'def':
                return Def()
            elif r_type == 'ghi':
                return Ghi()
            elif r_type == 'jkl':
                return Jkl()

What is a pythonic way to avoid if else here. I was thinking to create a dictionary with r_type being key and classname being value, and do a get of the value and instantiate, is it a proper way, or there is something better idiomatic way in python?

Aucun commentaire:

Enregistrer un commentaire