A scoping question

Premshree Pillai premshree.pillai at gmail.com
Tue Dec 28 14:50:24 EST 2004


On Tue, 28 Dec 2004 19:34:36 GMT, It's me <itsme at yahoo.com> wrote:
> This must be another newbie gotchas.
> 
> Consider the following silly code, let say I have the following in file1.py:
> 
> #=============
> import file2
> global myBaseClass
> myBaseClass = file2.BaseClass()
> myBaseClass.AddChild(file2.NextClass())
> #=============

You have declared myBaseClass to be global, but it doesn't exist.

Consider the following code:

global name
print name.__len__()

This will return a NamError

However, the following code will run just fine:

global name
name = "python"
print name.__len__()

will return 6

> 
> and in file2.py, I have:
> 
> #=============
> global myBaseClass
> class BaseClass:
>     def __init__(self):
>         self.MyChilds = []
>      ...
>     def AddChild(NewChild):
>         self.MyChilds.append(NewChild)
>     ...
> class NextClass:
>     def __init__(self):
>         for eachChild in myBaseClass.MyChilds:  # <- ERROR
>             ...
> #=============
> 
> When I run this, Python complains that myBaseClass is undefined in the last
> line above.
> 
> What am I doing wrong?  (Yes, I know I am thinking too much in C).  I
> thought the global declaration would have been sufficient but it's obviously
> not.
> 
> Thanks,
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

HTH

-- 
Premshree Pillai
http://www.livejournal.com/~premshree



More information about the Python-list mailing list