In matlab, I can create a structure array (struct) by doing the following.
person.name = 'Mike';
person.age = 25;
person.gender = 'male';
wherein person is not defined prior to creating the struct. When I try to do it in python, it gives me an error
name 'person' is not defined
Is there a similar way of doing it in python? Thanks
EDIT: Being new to python, I still think in matlab. The problem that I have is that I have a function that will take multiple inputs (more than 40), so instead of having function(input1,input2,…,input40), I will just have function(input) where the input consist of input.1, input.2,.., input.40.
Python won’t magically create a container object when you start assigning attributes to it, and if matlab allows this, I’d consider matlab badly broken. Consider this:
Now we have two objects,
personandpersom, andpersondoesn’t haveage, and there was no hint that this happened. Later you try to printperson.ageand, one would hope, matlab then complains… two pages after the actual mistake.A class can itself be used as a container or namespace. There’s no need to instantiate it, and it’ll save you a bit of typing if you just want a bundle of attributes.
To access or modify any of these, you can use
person.name, etc.N.B. I used a class for
sexas well to illustrate one of the benefits of doing so: it provides consistency in data values (no remembering whether you used “M” or “Male” or “male”) and catches typos (i.e. Python will complain about sex.mlae but not about the string “mlae” and if you were later checking it against “male” the latter would fail).Of course, you still run the risk of misspelling
name,age, orsexin this type of class definition. So what you can do is use the class as a template and instantiate it.Now when you do:
or if you want to document what all those parameters are:
it is pretty much impossible to end up with an object that has a misspelled attribute name. If you mess it up, Python will give you an error message at the point you made the mistake. That’s just one reason to do it this way.