Here is my solution to the previous problem.
Now, let's define the object with a new class
.
class InstrumentData:
"""
This class defined the instrument data
"""
def __init__(self, **data):
self.__data = data
def get_time(self, var):
return [tpl[0] for tpl in self.__data[var]]
def get_variable(self, var):
return [tpl[1] for tpl in self.__data[var]]
def integrate_trapezoid(self, var):
x, y = list(map(list, zip(*self.__data[var])))
return sum(0.5*(x[i] - x[i-1])*(y[i] + y[i-1]) for i in range(1, len(x)))
And then let's rewrite the read_instrument_data
function to work with this new class:
def read_instrument_data(filename):
instrument_data = {}
with open(filename) as f:
for record in f:
var,time,value = record.split(',')
if var not in instrument_data:
instrument_data[var] = []
instrument_data[var].append((float(time), float(value)))
return InstrumentData(**instrument_data)
And now we can an instance of the InstrumentData
class:
instrument_data = read_instrument_data('instrument1.csv')
Let's try our this solution and compare with our previous results.
x = instrument_data.get_time('A')
x
y = instrument_data.get_variable('A')
y
instrument_data.integrate_trapezoid('A')
Looks correct!
Together, the read_instrument_data
function and the InstrumentData
class work together to hide the structure of the data from the user. Once the data is handed off to the object, the user never sees it again. It is never passed explicitly between functions, and therefore there is no temptation to modify the data directly. This is safer, and if you want to eventually let the user add to or modify the data, you can add functions to the InstrumentData class to allow that. But the class itself controls how the user interacts with the data in a way that is (hopefully) more intuitive.