jeudi 6 juin 2019

Design pattern for relational and optional parameters?

I am to build a class that accepts a series of inputs via the constructor method, then perform a calculation with calculate() using these parameters. The trick here is that these parameters might be available sometimes and other times might not. There however, is a given equation between the variables, such that the missing ones can be calculated from the equations. Here is an example:

I know that:

a = b * c - d 
c = e/f

I am to calculate always a+b+c+d+e+f

Here is what I have so far:

class Calculation:
  def __init__(self, **kwargs):
    for parameter, value in kwargs.items():
      setattr(self, '_'.format(parameter), value)

  @property
  def a(self):
    try:
      return self._a  
    except AttributeError:
      return self._b * self._c - self._d


  @property
  def b(self):
    try:
      return self._b  
    except AttributeError:
      return (self._a + self._d) / self._c

... // same for all a,b,c,d,e,f 

  def calculate(self):
    return sum(self.a+self.b+self.c+self.d+self.e+self.f)

then use as:

  c = Calculation(e=4,f=6,b=7,d=2)
  c.calculate()

however, some other time might have other variables like: c = Calculation(b=5,c=6,d=7,e=3,f=6) c.calculate()

My question is: What would be a good design pattern to use in my case? So far, it seems a bit redundant to make a @property for all variables. The problem it must solve is to accept any variables (minimum for which calculation is possible) and based on the equation I have, figure out the rest, needed for calculation.

Aucun commentaire:

Enregistrer un commentaire