usage of __import__ across two files

Fredrik Lundh fredrik at pythonware.com
Sun Dec 12 10:18:10 EST 2004


"bwobbones" wrote:

>  I'm having trouble making __import__ work with the two classes attached. The PrintHello() method 
> can't be seen in the BMTest2 class - what am I doing wrong here?

in those three lines, most about everything, I'd say ;-)

let's see, "PrintHello" is a method of the BMToolBar class.  to call a method, you need
an instance of that class, which is what the "works just fine" line you've commented out
attempts to create (except that it won't work, because that class is defined in another
module).  instead, you import the module using the __import__ implementation hook
rather than a plain "import", and then you attempt to call a method on an object that
doesn't exist.

> ****************************
> class one - BMTest - in BMTest.py:
> ****************************
> import wx
> from traceback import print_exc
>
> class ImportTest(wx.Frame):
>    def __init__(self):
>        wx.Frame.__init__(self, None, -1, "ImportTest",
>                          size = (666,480), style = wx.DEFAULT_FRAME_STYLE)

here comes the confusing part:

>        #tb = BMToolBar(self) # works just fine!
>        tb = __import__('BMTest2')
>        tb2.PrintHello()

things should work a bit better if you replace these three lines with

        import BMTest2
        tb = BMTest2.BMToolBar(self)
        tb.PrintHello()

(import the module holding the class, create an instance of the class, and call a
method on that instance)

> class MyApp(wx.App):
>    def __init__(self, flag):
>        wx.App.__init__(self, flag)
>    def OnInit(self):
>        frame = ImportTest()
>        self.SetTopWindow(frame)
>        return True
>       if __name__ == '__main__':
>   try:
>       app = MyApp(False)
>       app.MainLoop()
>   except:
>       print print_exc()
>
> **************************
> class 2 BMTest2 - in BMTest2.py:
> **************************
> import wx
>
> class BMToolBar(wx.ToolBar):
>    def __init__(self, parentFrame):
>        wx.ToolBar.__init__(self, parentFrame, -1, 
> style=wx.TB_HORIZONTAL|wx.NO_BORDER|wx.TB_FLAT|wx.TB_TEXT)
>        print "*** gday ***"
>        self.Realize()
>       def PrintHello(self):
>        print "Hello"

</F> 






More information about the Python-list mailing list