0

I have a problem off which I have put the basic dynamics into a class. It has got a lot of constants and methods. Some made up example is below:

class ProblemConstants:
  def __init__(self, fixed_cost, variable_cost):
     self.fixed_cost = fixed_cost
     self.variable_cost = variable_cost

  def cost_total(self):
      return fixed_cost + variable_cost

The problem can occur in different forms, with other dynamics and other solution methods. This required to implement several solution methods in different ways (e.g. different transition matrices or ways to call certain methods). I would like to have different classes for each of these cases, but only initiate the ProblemConstants once.

Example of extensions classes f.i.:

class ProblemEnvironment1(ProblemConstants):
   def __init__(self, *args, **kwargs, p):
       super().__init__(*args, **kwargs)
       self.p = p

   def transition_matrix(self):
       return np.outer(1-self.p, 1-self.p)

   def solve(self):
      return 3*self.fixed * self.transition_matrix()

class ProblemEnvironment2(ProblemConstants):
   def __init__(self, *args, **kwargs, q):
       super().__init__(*args, **kwargs)
       self.q = q

   def transition_matrix(self):
       return np.outer(self.q, self.q)

   def solve(self):
       return 999*self.transition_matrix()*self.variable_cost

What I now want to be able to do:

problem = ProblemConstants(
            fixed_cost = 2
            variable_cost = 3)

Env1 = ProblemEnvironment1(
                 problem, 
                 p=0.99)

Env2 = ProblemEnvironment2(
                 problem,
                 q = 0.35)

Env1.solve()
Env2.solve()

But now I gave the problem object as a input which I dont want. What i want to have is that both the environements have the same values for fixed_cost and variable_cost, wo/ me having to give the input constants to both of them, but only once.

So I just would like to extend my ProblemConstant to both cases.

weltensturm
  • 2,164
  • 16
  • 17
Rens
  • 177
  • 9
  • What you want to look into [using `**kwargs`](https://stackoverflow.com/questions/1769403/what-is-the-purpose-and-use-of-kwargs) for your constants, you might define `constants = {'fixed_cost': 2, 'variable_cost': 3}` and then `Env1 = ProblemEnvironment1(p=0.99, **constants)`, likewise for `Env2 = ProblemEnvironment1(p=0.35, **constants)`. Though you will need to define the parent class to accept any keyword argument that it doesn't care, e.g. `def __init__(self, fixed_cost, variable_cost, **kwargs):`. – metatoaster Jun 09 '20 at 09:30
  • Thanks for your answer, this was indeed the most practical way to solve this I think – Rens Jun 09 '20 at 14:06

0 Answers0