2

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!

1
  • Look up "factory pattern" Commented Sep 11, 2018 at 18:32

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the super helpful link. All of your examples (in the link) use a 'create' method, instead of just relying on init. Is there a reason for this?
__init__ is called on the already created object. To make class create an object of other class you have to modify __new__, not __init__. However, having such create is usually considered a better option, look up the "factory method" pattern.
-1. StackOverflow answers should be self-contained. I'd be happy to +1 if the answer contained the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.