[Tutor] function local var problem :-((
Lloyd Kvam
pythontutor at venix.com
Sun Oct 5 16:39:56 EDT 2003
A good site that lists some other Python pitfalls:
http://zephyrfalcon.org/labs/python_pitfalls.html
zephyrfalcon.org :: labs :: 10 Python pitfalls
#5 is using a mutable variable as a function default.
mjekl at clix.pt wrote:
> 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
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-443-6155
fax: 801-459-9582
More information about the Tutor
mailing list