Help on object scope?

Diez B. Roggisch deets at nospam.web.de
Sun Feb 25 17:17:46 EST 2007


> 
> Thank you for the advice, but that seems a bit unwieldy. My code will
> have about 10 of these global objects, all of which interact with
> eachother. It seems silly to have to pass 10 parameters around to each
> instance I work with. I hope there is a smarter way to do it, or
> perhaps someone can suggest a smarter way to code it.
> 
> Am I stuck with just having to put all the code in one file? That is
> what I wanted to avoid, because the file will get incredibly long. It
> seems like the only reason my code above failed is because there were
> two separate modules. Perhaps I just need to import /lib/q.py in a
> different way?

You can interact just fine, just qualify the objects with the module 
names. So in q, you need to use p.r instead of just r.

It's another question if this design is really good - relying on so many 
globals. It would certainly be better to have e.g. a class that looks 
like this:


import p
import q
class GlueThingy(object):
     def __init__(self):
         self.p1 = p.SomeObject(self)
         self.q1 = q.SomeOtherObject(self)


Then in SomeObject you can use the passed GlueThingy reference to access 
other instances:

class SomeObject(object):

     def __init__(self, glue):
         self.glue = glue

     def do_something(self):
         self.glue.q1.foobar()


Diez



More information about the Python-list mailing list