[Tutor] Silly Object Namespace Questions

Sean 'Shaleh' Perry shaleh@valinux.com
Thu, 24 May 2001 09:41:35 -0700 (PDT)


On 24-May-2001 Curtis Larsen wrote:
> <Sigh> OK I'm still trying to wrap my head around class namespace(s),
> and I know this is gonna sound dumb, (BUT) I have a few questions about
> the following example:
> 
> class object1:
>    def __init__(self):
>       a = 10
>       self.x = 1
>    def doit(self):
>       self.str = "This is a string"
>       wumpus = "Gotcha!"
>       print wumpus
> 
> 
> Doing a "dir(x)" produces  "['x']", and after running "self.doit()"
> (which prints "Gotcha!"), "dir(x)" gives "['str', 'x']".  Okay, soooo:
> 
> 
> 1. What namespace(s) do "x", "a", "str", and "wumpus" respectively
> belong to?
> 

x and str are variables owned by the class instance 'self'.  a and wumpus are
temporary variables that live as long as the namespace where they are declared
(i.e. the function call).  Every time doit() is called a new variable called
'wumpus' is defined.  Same goes for __init__() and 'a'.

> 2. Why isn't "a" visible?  (I know it relates to #1.)
> 

because it is a local variable in the function.

> 3. Although (I believe) "x" and "str" are "safe" from modification,
> would another instance of "object1" change the value of "a" or
> "wumpus"?
> 

yes, but not for why you are thinking.  Each object's doit() will create a new
variable called 'wumpus' when called.  This variable lives for as long as it
takes for doit() to execute, then it goes away.

> 4. Is using "undeclared" variables such as "a" and "wumpus" the best
> way to temporarily manipulate data within an object instance without
> "publishing" that data for external use?  (For example, you can print
> "wumpus", or do calculations on "a", but no one can get at them
> externally.)
> 

depends on what you are trying to do.  If you want temporary variables, then
yes.  If you need the variable to live between function calls, then no.

> 5. Is there anything "wrong" with defining "x" on it's own?  (I've
> usually seen such defined in the parm list of "__init__".)
> 

Putting it in the param list lets it be specified when object1 is created. 
There is no reason it can not simply start with a sane value and be modified by
later function calls.  For instance:

class Counter:
  def __init__(self):
    self.count = 0
  def incr(self):
    self.count = self.count + 1
  def value(self):
    return self.count


> 6. What function(s) can I use to see/list methods such as "doit" within
> an instance?  ("vars()" and "dir()" don't do it.)
> 

not sure on this one, sorry.