[Tutor] function local var problem :-((

mjekl at clix.pt mjekl at clix.pt
Sun Oct 5 16:15:07 EDT 2003


Hi,

I'm new here and with programming. I've been learning on my own and cannot
understand what happens with this function I created.

The function is in it's own module that I import into shell.

###### module1.py ######

def printHierarchy(objecto, printList=[]):
   """Prints a class hierarchy given an object.
      Works only with single inheritance hierarchies."""

   if objecto.__class__.__bases__:
      printList.append(objecto.__class__.__name__)
      recurObjecto = objecto.__class__.__bases__[0]()
      return printHierarchy(recurObjecto, printList)
   else:
      printList.append(objecto.__class__.__name__)

      if not objecto.__class__.__bases__:
	 i = 0
	 for klass in printList:
	    print i * ' ' + klass
	    i += 1
      else:
	 return printList

####################

in shell I created a hierarchy of three classes:
class Sup; class Sub1(Sup); class Sub2(Sub1)

Then:
>>> oSub2 = Sub2()
>>> printHierarchy(oSub2)
Sup
   Sub1
      Sub2
>>>

The problem is that if I call the function again I get:
>>> printHierarchy(oSub2)
Sup
   Sub1
      Sub2
	 Sup
	    Sub1
	       Sub2
>>>

The problem to me is that I think that the var printList is local and that
it is initialized every time the function is called. But results contradict
this assumption. So I tried to investigate the namespaces and found no
references to var printList. I guess my investigation is bad (In shell I
issued dir() and dir(module1)
and got nothing. Also tried to use:
 from module1 import printHierarchy
But didn't work either. Can someone please help me?

Python 2.2 winXP

Txs,
Miguel

Clix Rapidix - Aumente até 6X a velocidade da sua Internet
Adira em http://acesso.clix.pt e comece logo a navegar



More information about the Tutor mailing list