Namespace troubles

Alan algotrhythm at gmail.com
Fri Nov 16 16:03:47 EST 2007


<snip>
> class MyFrame(wx.Frame):
>     def __init__(self, parent, id, title):
>         wx.Frame.__init__(self, parent, id, title, size=(600,500))
>
>         nb = wx.Notebook(self)
>         self.page1 = Form1(nb, -1)
>         nb.AddPage(self.page1, "Choose Patient")
>         self.page1.SetFocus()
>
>     def patient_lookup(self, first_ltrs):
>         self.page2 = Selectable.Repository(nb, -1, first_ltrs)
>         nb.AddPage(self.page2, "Patient Lookup")
>         self.page2.SetFocus()
>
<snip>

> I'm getting an error from the patient_lookup function:  "global name
> 'nb' is not defined".  I don't understand how a function in the same
> class cannot see the wx.Notebook instance "nb".  I know it exists
> somewhere I just haven't found the name for it.  I've tried
> "frame.nb", "self.nb", f = GetTopLevelParent(self) then f.nb.  How can
> an instance of something just disappear?
>
> Thanks for any help.
>
> Mike

nb is a local variable within the __init__() method only.

This is the same as, e.g.:

def foo():
    i = 0

def bar():
    print i

The use of i in bar() is an error, because it is only assigned in
foo()


If you want to make it available to all methods within a class then
you need to attach it to the instance of that class, e.g.:

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(600,500))
        self.nb = wx.Notebook(self)
        self.page1 = Form1(nb, -1)
        self.nb.AddPage(self.page1, "Choose Patient")
        self.page1.SetFocus()

    def patient_lookup(self, first_ltrs):
        self.page2 = Selectable.Repository(nb, -1, first_ltrs)
        self.nb.AddPage(self.page2, "Patient Lookup")
        self.page2.SetFocus()


--
Alan



More information about the Python-list mailing list