In writing a python object factory, I'm running into a lot of parameter repetition in the constructors. It feels wrong, like there is a better way to use this pattern. I'm not sure if I should be replacing the parameters with **kwargs
or if there is a different design pattern that is more suited to this sort of case.
A simplified example is below. The real code is of course more complicated and you can see more reasons why I'd do it this way, but I think this is a reasonable Minimal Reproducible Example
External to these classes, for the API, the most important factors are species
and subspecies
. It happens to be that internally, is_salt_water
is important and results in a different object, but that's an internal matter.
class Fish:
def __init__(self, species, sub_species, length, weight): # Repeating this a lot
self.species = species
self.sub_species = sub_species
self.length = length
self.weight = weight
self.buoyancy = self.buoyancy()
def buoyancy(self):
raise Exception("Do not call this abstract base class directly")
class FreshWaterFish:
def __init__(self, species, sub_species, length, weight): # Repeating this a lot
self.fresh_water = True
super().__init__(species, sub_species, length, weight) # Repeating this a lot
def buoyancy(self):
self.buoyancy = 3.2 * self.weight #totally made-up example. No real-world meaning
class SaltWaterFish:
def __init__(self, species, sub_species, length, weight): # Repeating this a lot
self.fresh_water = False
super().__init__(species, sub_species, length, weight) # Repeating this a lot
def buoyancy(self):
self.buoyancy = 1.25 * self.weight / self.length #totally made-up example. No real-world meaning
def FishFactory(self, species, sub_species, length, weight, is_salt_water = False): # Repeating this a lot
mapper = {True : FreshWaterFish, False: SaltWaterFish}
return mapper[is_salt_water](species, sub_species, length, weight) # Repeating this a lot
Aucun commentaire:
Enregistrer un commentaire