A scoping question
It's me
itsme at yahoo.com
Tue Dec 28 15:22:12 EST 2004
Thanks, Steve.
So, global is only to within a module (I was afraid of that). Those words
flashed by me when I was reading it but since the word "module" didn't
translate to "file" in my C mind, I didn't catch that.
In that case, you are correct that I have to do an import of file1 in file2.
Not that this is not real code, I am still trying to learn the ins and outs
of Python by writing some silly code - but will be important to help me
understand how I would write the real code.
Regarding the question of not placing everything in one module, I wouldn't
think that that's how I would do it. I might get ambitous later and write
code for a larger project. In that case, I will need to know more about
scoping across multiple modules. So, this helps me understand what to do.
Thanks again.
"Steven Bethard" <steven.bethard at gmail.com> wrote in message
news:I5jAd.246742$5K2.73425 at attbi_s03...
<snip>
>
> I think you're confused about what the global keword does. Declaring a
> name as global makes that name global *to the module*:
>
> http://docs.python.org/ref/global.html
> http://docs.python.org/lib/built-in-funcs.html#l2h-32
>
> What you probably want instead is:
>
> -------------------- file1.py --------------------
> import file2
> myBaseClass = file2.BaseClass()
> myBaseClass.AddChild(file2.NextClass())
> --------------------------------------------------
>
> -------------------- file2.py --------------------
> class BaseClass:
> def __init__(self):
> self.MyChilds = []
> def AddChild(self, NewChild):
> self.MyChilds.append(NewChild)
> class NextClass:
> def __init__(self):
> from file1 import myBaseClass # IMPORT
> for eachChild in myBaseClass.MyChilds:
> pass
> --------------------------------------------------
>
> Note that I import myBaseClass in __init__. If I imported it at the top
> of the module, then file1 would import file2 which would then import
> file1 and you'd have a circular dependency.
>
> As it is, your code is very tightly coupled. Why don't you put all this
> code into a single module?
>
> Steve
More information about the Python-list
mailing list