Yoriz wrote:I don't think you really want 100 people floating around your namespace
I take it this would be a bad thing for me to do..
Why is that?
- It pollutes the namespace. Suddenly you have a lot of variables to deal with. Say you want to examine the namespace to see if specific value are there (e.g. while debugging), now you'll get a massive dict scrolling off the edge of your terminal.
- It is harder to work with. How do you know there are 100 and not 140, or that they're all there? To determine that you'll have to keep examining the namespace (which, in Python, amounts to manipulating a dict anyway).
- Conceptually, those variables are a part of a "collection", so they should actually be a part of a collection. Say you want to do something to all of them (e.g. print them out or write them to a file). Now you have to pass 100 arguments to your output function (or else, *shudder*, have 100 globals). What if you want to add 101st person? Now you have to modify it in a bunch of places; and make sure you modify it in *all* the places -- otherwise you won't get an error, but your code will be subtly wrong (e.g. your output file won't contain the 101st person).
If all your elements are in a collection, you can pass them around as a single variable, you can iterate over all of them (without caring exactly how may there are), you can easily check if an element is already present, etc.
Also, a note about object "names". Variables are external to the objects they refer to. So here
- Code: Select all
person1 = Person()
You do not have a Person object called "person1". You have a variable called "person1" that is referring (at this point in the code) to a nameless Person object. If you want your persons to have meaningful names, you should store the name as an attribute of the object itself. If you don't need meaningful names but just need an identifier unique to the person, then all Python objects already have an id which you can access with the built-in id() function (though you almost never need to do that).