This is a question to question 912526 - How to pass many variables to and from a function in Python? .
In the program I am writing, I need to pass all the variables, and from my previous question I understand that I have to put these variables in classes, and then bypass the classes.
Some of these variables are included in repeating sets - to calculate a thin film I need to track the optical properties (refractive index, absorption, thickness, etc.) for several layers.
Is the best way to store variables like this to create a class derived from a Python list, to store a set of classes, each of which contains variables for a single layer? And then put the functions that are associated with the set of layers in the class obtained from the list, and the functions that belong to a specific layer in this class? Is there a better way to do this with a single class?
Using the two-class approach in the following example, I can configure everything so that I can access variables using statuses such as
n1 = layers[5].n
This is the best way to do this, right?
#Test passing values to and from functions class Layers(list): def add(self,n,k,comment): self.append( OneLayer(n,k,comment) ) def input_string(self): input_string = [] for layer in self: vars = layer.input_string() for var in vars: input_string.append( var ) return input_string def set_layers(self,results): for layer,i in enumerate(self): j = i*layer.num_var layer.set_layer( *results[j:j+2] ) class OneLayer(object): def __init__(self,n,k,comment): self.n = n self.k = k self.comment = comment def input_string(self): return [['f','Index of Refraction',self.n], ['f','Absorption',self.k],['s','Comment',self.comment]] def set_layer(self,n,k,comment): self.n = n; self.k=k; self.comment = comment def num_var(self): return 3 if __name__ == '__main__': layers = Layers() layers.add(1.0,0.0,'This vacuum sucks') layers.add(1.5,0.0,'BK 7 Glass') print layers[0].n print layers.input_string() layers[1].set_layer(1.77,0.0,'Sapphire') print layers.input_string()
I get the following result from this test program:
1.0 [['f', 'Index of Refraction', 1.0], ['f', 'Absorption', 0.0], ['s', 'Comment', 'This vacuum sucks'], ['f', 'Index of Refraction', 1.5], ['f', 'Absorption', 0.0], ['s', 'Comment', 'BK 7 Glass']] [['f', 'Index of Refraction', 1.0], ['f', 'Absorption', 0.0], ['s', 'Comment', 'This vacuum sucks'], ['f', 'Index of Refraction', 1.77], ['f', 'Absorption', 0.0], ['s', 'Comment', 'Sapphire']]