agf1997
agf1997

Reputation: 2898

How do I create a python class with nested data?

I'm trying to figure out how to construct a class in python where I have nested variables.

In practice, we are measuring a thing called a "Device". Each "Device" has multiple physical measurement locations called "Wells". And each "Well" in measured at various time "Intervals".

I've been trying to create a class in Python to create an object called a "Device". Each device may have multiple "Intervals" which I've placed into a list. The part I'm having difficulty with is how I can associate the measurement data from a particular well with a specific interval.

My data looks something like this:

Device1 -> 0hr -> Well 1 -> Data
Device1 -> 0hr -> Well 2 -> Data
Device1 -> 1hr -> Well 1 -> Data
Device1 -> 1hr -> Well 2 -> Data

It's worth noting that the number of intervals and number of wells for each device is variable.

I know it's not much but here's what I have so far.

class device(object):
    def __init__(self, name):
        self.name = name
        self.intervals = []

    def add_interval(self, interval):
        self.intervals.append(interval)

def main():
    d1 = device('Control')
    d1.add_interval(0)
    d1.add_interval(24)
    d1.add_interval(48)
    print(d1.intervals)

Any suggestion would be greatly appreciated.

Upvotes: 0

Views: 146

Answers (1)

Manali
Manali

Reputation: 246

If you are looking for a class based design, you could go for something like this:

    class interval():
        def __init__(self, interval, wells):
            self.interval = interval
            self.wells = wells

    class well():
        def __init__(self, name, data):
            self.name=name
            self.data = data

    class device(object):
        def __init__(self, name):
            self.name = name
            self.intervals = []

        def add_interval(self, interval_value):
            self.intervals.append(interval(interval_value))

    def main():
        d1 = device('Control')
        d1.add_interval(0)
        d1.add_interval(24)
        d1.add_interval(48)
        print(d1.intervals[1].interval)

In this way you'll be able to access the data w.r.t hierarchy. Of course you'll have to add more methods for it to work properly. I am just giving a rough idea. Or you can also use a dict based storage where your intervals are dicts and the wells inside them are also keys and the data related to those wells are values. It would be simpler but can get cluttered if there's more entities in play.

Upvotes: 1

Related Questions