[Tutor] Another question on global variables...

alan.gauld@bt.com alan.gauld@bt.com
Thu, 17 Oct 2002 13:57:40 +0100


> Alan - regarding your OO example, if I have to assign the result to an
> external variable, isn't that the same as a global? 

It might be, or more likely it would be a local variable 
within another function, or an instance variable in 
another object.

> >------- OO Example ------
> >
> >class ABC:
> >   self.abc = []
> >   def set_it(self): self.abc = [1,2]
> >   def get_it(self): return self.abc
> >
> >foo = ABC()
> >foo.get_it()  # prints initial empty list
> >foo.set_it()    # sets new list
> >print foo.get_it()  # prints new value
> >---------------------------

> >...you can assign the result to a variable outside
> >the function - or print it...

------ Extending above example -----

class XYZ:
  def doit(self, anABC):
    myVar = anABC.get_it()   # assign value of ABC.abc to myVar
    return str(myVar)
  def another(self, anABC):
    if len(anABC.get_it()) == 0:  #is empty
       anABC.set_it()
    print anABC.get_it()
  def internaluse(self,anABC):
    self.abc = anABC.get_it()

x = XYZ()
print x.doit(foo)  #--> '[1, 2]'
x.another(foo)     #--> [1,2]
x.internalize(foo) # no output
print x.abc        #--> [1, 2]
---------------------------------

[ NB This is actually bad OO design since much of 
  what XYZ is doing should be done by methods in 
  ABC... ]

This illustrates how to use the variable passing 
mechanisms well enough I hope....

Alan G.