I am converting a MATLAB script into python. The MATLAB script uses some kind of objects hierarchy for different input variables as in:
parameterA.subparameter1= A1;
parameterA.subparameter2= A2;
parameterB.subparameter1= B1;
parameterB.subparameter2= B2;
Where A1,A2,B1,B2
can all be strings and numbers. I wish to convert this to python and I have used
parameterA.subparameter1= A1
parameterA.subparameter2= A2
parameterB.subparameter1= B1
parameterB.subparameter2= B2
Now I am getting the error:
NameError: name 'parameterA' is not defined
I have tried to initialize them by using either parameterA,parameterB=[],[]
, which is not good because I want objects and not a list or parameterA,parameterB=set(),set()
according to this post as well as some other solution.
Is this at all the correct approach? How do I initialize this structure? Is there a better way to do this?
I would strongly suggest that you use dict
s instead. These are efficient and versatile built-in objects in python.
parameterA = {'subparameter1': A1} # definition
parameterA['subparameter2'] = A2 # update/assignment
parameterB = {'subparameter1': B1, 'subparameter2': B2}
As you can see you can access and modify values using square brackets. If you really insist on using attribute lookup, you could use types.SimpleNamespace
:
from types import SimpleNamespace
parameterA = SimpleNamespace(subparameter1=A1)
parameterA.subparameter2 = A2
parameterB = SimpleNamespace(subparameter1=B1, subparameter2=B2)
The main reason I'd stick to dicts is the ease with which you can access keys dynamically. Only use a SimpleNamespace
or something similar if you never access attributes programmatically, because your objects are more like a tool for grouping variables together. You can still access attributes programmatically, but it's uglier (and less idiomatic) than dict
item lookup.