Hello everybody,
I have a (hopefully) simple question about scoping in python. I have a
program written as a package, with two files of interest. The two
files are /p.py and /lib/q.py
My file p.py looks like this:
---
from lib import q
def main():
global r
This statement only means that all assignments/binding to the name
"r" take place at the level of the "p" file.
r = q.object1()
s = q.object2()
Whereas, "s" here is strictly local to the scope of "main" (and not
to the file "p")
My file q.py in the subdirectory lib looks like this:
class object1:
t = 3
class object2:
print r.t
There is no "r" object in the scope of file "q". Furthermore, your
object2 class can only access a single instance of "r" regardless of how
many object1 class instances are created...
r1 = q.object1()
r2 = q.object1()
These will never be seen by any instance of object2. If object2
instances really need a particular object1 instance, they should create
that instance internally, or accept it as part of the initialization
call...
s = q.object2(r)
Python gives me an error, saying it can't recognize global name r.
However I define r as global in the top-level main definition! Can
anyone suggest how I can get around this, if I want to define and bind
global names inside of main() which are valid in all sub-modules?
The common method is to put ALL "globals" into a module (file) of
their own, import that module into all other modules (files) that need
the objects, and reference the objects using fully qualified (that is,
do NOT use "from module import ...", only use "import module") name.
The above:
common.py
-=-=-=-=-=-=-
r = None #just a placeholder
p.py
-=-=-=-=-=-
import common
import q
common.r = q.object1()
q.py
-=-=-=-=-=-
import common
....
print common.r.t
Also, your example Classes don't show any code for use of class
instances. No "self...." for instance data. Is that a result of
simplifying for this query, or is that your actual understanding of how
to write classes?
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/