chadh
chadh

Reputation: 125

Instantiate different class based on user input

I am trying to write an extensible python code to implement several different optimization algorithms. I am not very experienced in object oriented programming, so my question may be worded incorrectly, but I think I am struggling with setting up inheritance and/or polymorphism in my code.

I want to be able to chose between several different optimization alogrithms based on user input. My first inclination was to write a Optimizer class, which would hold all of the common info, then have specific classes for each algorithms which inherit the Optimizer class. ie.

class Optimizer:
    def __init__(self, user_input):
        pass

class Method1(Optimizer):
    def__init__(self, user_input):
        pass
    def run()
        pass

class Method2(Optimizer):
    def__init__(self, user_input):
        pass
    def run()
        pass

I quickly realized that you need to know which method you are going to use before initializing the optimizer. This isn't the end of the world, but it seems cleaner to parse the user input in the initialization of the optimizer object. I would like to be able to initialize the optimizer with something like:

optimizer = Optimizer(user_input)

with the resulting optimizer having the correct behavior based on a 'method' field embedded in the user_input file.

What is the best way to do this such that I don't have to go back a re-write a bunch of switch statements when I add a new method?

Thanks!

Upvotes: 2

Views: 2852

Answers (1)

Vadim Pushtaev
Vadim Pushtaev

Reputation: 2353

I have the article addressing exactly this topic.

In short, you better predeclare how user input maps into a class. For it you can use:

  • Explicit mapping
  • Dynamic class name generation
  • Registry and class decorator
  • Custom metaclass
  • Init subclass hook

For more details, read the article I've mentioned above.

Upvotes: 2

Related Questions