don't understand namespaces...

Dave Angel davea at ieee.org
Thu Apr 30 21:01:46 EDT 2009


Lawrence Hanser wrote:
> Dear Pythoners,
>
> I think I do not yet have a good understanding of namespaces.  Here is
> what I have in broad outline form:
>
> ------------------------------------
> import Tkinter
>
> Class App(Frame)
>       define two frames, buttons in one and Listbox in the other
>
> Class App2(Frame)
>       define one frame with a Text widget in it
>
> root = Tk()
> app = App(root)
> win2 = Toplevel(root)
> app2 = App2(win2)
> root.mainloop()
> ------------------------------------
>
> My understanding of the above goes like this:
> 1) create a root window
> 2) instantiate a class that defines a Frame in the root window
> 3) create another Toplevel window
> 4) instantiate another class that defines a frame in the Toplevel window (win
> What I cannot figure out is how to reference a widget in app2 from app...
>
> I hope this is sort of clear.
>
> Any assistance appreciated.
>
> Thanks,
>
> Larry
>
>   
A couple of things about your message confused me greatly, but I think I 
can help anyway.

1) please don't call window classes "AppXX", since an App has a very 
different meaning in GUI parlance.
2) namespaces are very different than what you're asking, as they 
describe how symbols are searched when they're not directly accessible 
within the class or within a function.

Anyway, back to your real question:  Since you're instantiating 
subclasses of Frame, you have control of the __init__() method.  There 
already is a "parent" parameter, so save it as a instance attribute.  
That gets you upward references.  And the caller gets a return value 
from the constructor, which is a downward reference.

If you pick a consistent naming, you can simply walk the objects with 
dot notation.  I find it easiest if each class usually instantiates all 
its own children, and therefore saves instance attributes of each of 
them.  If you followed that convention, then app2 could find app by 
using    self.parent.parent.app

Another approach is to create one extra class object which holds 
references to everything needed.  Then each child is passed a reference 
to that instance in its constructors.  The problem with this is that 
everything gets a bit too tightly coupled.

Usually some combination works best.

DaveA



More information about the Python-list mailing list