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.
In many languages you can create an object without creating a data type, and add properties to that object. For example in JS or AS: var myObject = {}; myObject.
No, there is no such a feature, you have to type out the full type name(class name).
We already know that an object is a container of some data and methods that operate on that data. In Python, an object is created from a class. To create an object, you have to define a class first.
We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.
In Python you can add members dynamically to an object, but (1) the name must already exist (it must have been assigned) and (2) it must be bound to an instance of some class. To do so you may create an empty class:
class Empty:
pass # empty statement otherwise the class declaration cannot succeed
construct an instance of it and assign it to your variable
person = Empty()
and then add whatever data you want
person.name = 'Mike'
person.age = 25
person.gender = 'male'
On the other hand, if you don't need the additional features a "normal" class provides and you just want to store some data in a key=>value fashion you should probably just use a dictionary.
person={}
person['name']='Mike'
person['age']=25
person['gender']='male'
(notice that, at least up to Python 2.7, this is mostly just a stylistic/syntactic difference, since instance members are implemented underneath in terms of dictionaries)
As a general guideline, you want classes when you are instantiating multiple objects made in the same way (and where typically the assignment to the members is done in the class constructor; adding members later generally makes for difficult to follow code), dictionaries otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With