Newbie help- Can multiple instances with multiple names automatically created.
Dave Angel
davea at ieee.org
Tue Jan 5 00:28:58 EST 2010
(You top-posted. It's polite on most newsgroups, and specifically on
this one to add your comments *following* the quoted earlier text)
Nav wrote:
> Okay, let me ask another question:
>
> When we create instances of objects by doing
> x = className ()
> are we using globalnamespace?
>
>
If that line appears at top-level, it uses the global namespace for the
symbol x. If it's inside a class, or inside a function, then it uses
some other namespace. The risk for globals is mainly that the namespace
gets "polluted", or full of unrelated symbols, which sooner or later are
going to collide. And this is made much worse if someone is creating
such names indirectly, by monkeying with the non-portable constructs
such as global(), or by doing from mymodule import * There are
other risks, but this is a short message.
As far as I know, there's very little performance cost for having lots
of stuff in globals. It's just bad practice because it frequently leads
to bugs.
> if yes then:
> if using globalnamespace is bad then why does every book or tutorial
> about python classes give the above style of assignment as an
> example?
>
>
Beginner books keep things simple. Besides the same statement is great
if it's in a function. And it's usually a small step for the beginner
to start moving stuff from the top-level of the module into named
functions. And eventually to functions that are small enough to be
maintainable.
> Second why do we use a dictionary to create something like this? I
> know how it works, but what is wrong with simply creating instances
> automatically? Once created the data for the instances is
> automatically saved in their own space? Why have a round about way
> using dictionaries?
> Is there an advantage or does it conflict with something else?
>
>
What? Automatically where? What's roundabout about dictionaries?
> Why not have
> for i in specialList: #I presume it would have to be special, because
> it can't be a problematic type
> i = className(whatever)
>
>
>
Once you bind a new value to i, it no longer has any relationship to the
value which was in specialList. Perhaps you want something like:
for i in xrange(len(specialList)):
specialList[i] = className(...)
which will replace the present values in specialList with instances of
className.
>
>
>>> what are the risks of globalnamespace use
>>>
>> You're unnecessarily tying your code to the implementation.
>>
>>
>>> and what are the benefits?
>>>
>> Absolutely none that using a dictionary doesn't also give you.
>>
>
>
>
More information about the Python-list
mailing list