mardi 8 août 2023

How to best model a bi-directional association between two classes iny my python code

I have a numerical model that models some physical quantities. Now to analyse and administer the results of said model I am writing some python infrastructure code. The basic concepts I have are that of a model run (identified by its timestamp) and that of a quantity (identified by its name). As said each model run contains multiple quantities and a quantity can appear in multiple model runs.
My idea is thus to model the relationship between a model run and a variable by utilizing an additional class DataPoint.

The basic setup would look like this:

class ModelRun:
    def __init__(self,timestamp):
        self.timestamp = timestamp
class Quantity:
    def __init__(self,name):
        self.name = name
class DataPoint:
    def __init__(self,model_run,quantity):
        self.model_run = model_run
        self.quantity = quantity

Now like this the structure is of course not navigable. This could be solved by adding a list of datapoints to both the ModelRun as well as Quantity class like so:

class ModelRun:
    def __init__(self,timestamp):
        self.timestamp = timestamp
        self.data_points = []
class Quantity:
    def __init__(self,name):
        self.name = name
        self.data_points = []
class DataPoint:
    def __init__(self,model_run,quantity,data):
        self.model_run = model_run
        self.quantity = quantity
        self.data = data
        quantity.data_points+=[self]
        model_run.data_points+=[self]

Is this a useful pattern? From my gut feeling it is a bit strange to modify instances of Quantity and ModelRun from within the DataPoint.__init__ method. As my ModelRun and Quantity classes wil get more complex and be used in a lot of other parts of my code I am very much afraid to introduce some unnecessary mistakes at this stage.
Any suggestions appreaciated, thanks!

Aucun commentaire:

Enregistrer un commentaire