[Tutor] Silly Object Namespace Questions

D-Man dsh8290@rit.edu
Fri, 25 May 2001 11:19:25 -0400


On Fri, May 25, 2001 at 09:06:47AM -0500, Curtis Larsen wrote:

<snip>

| > On 24-May-2001 Curtis Larsen wrote:
| >> 
| >> class object1:
| >>    def __init__(self):
| >>       a = 10
| >>       self.x = 1
| >>    def doit(self):
| >>       self.str = "This is a string"
| >>       wumpus = "Gotcha!"
| >>       print wumpus
| 
| Thanks (to everyone) -- that makes it all much more understandable. 
| One thing I'm still missing though, is whether or not different
| instances of the above example class will overwrite the "a" or "wumpus"
| variables.  In other words, is the namespace for both those variables
| shared amongst the different instances, and will one instance (possibly)
| changing the the value of, say, "a" mean that another instance will also
| perceive the change?
| 
| If it helps, what I'm looking for is the best way to use "temporary"
| calculation ("working") variables within a class (or methods of that
| class) without callers seeing those variables (unlike the "x" variable
| above).  "a" and "wumpus" appear to be good examples of doing this very
| thing, but if different instance will step on each others values for
| them, it would be... ummmm... "bad".

'a' and 'wumpus' are local variables.  Their scope is only in the
method and they only exist for the duration of the method.  Once the
method returns they disappear.  Since any given method invocation only
occurs once (you can invoke the same method many times, but each
invocation is a separate invocation) those variables are only
accessible from that invocation.  Each invocation has its own local
variables.

The conclusion is yes, that is the way to make "temporary" (usually
called 'local :-)) variables for intermediate operations.

| One other question: If you have an import statement within a method or
| function, how often does the import actually occur?  Once upon
| instantiation?  Every time the function/method is called?  Only once
| ever? (Wow!  Not *that* would be a nifty pre-parser!)

The import statement is executed each time it is reached (for each
invocation of that method ).  When an import statement is executed the
first thing it does is check the cache of already imported modules.
If the module has already been imported then it is not imported again.
It is similar to your last guess, but if the method is never called
the module won't be imported at all.

(Also be sure _not_ to use the  from <module> import *   form except
 maybe at module level.  It is even better to not use it at all.)

-D