usage of __import__ across two files

bwobbones bwobbones at gmail.com
Mon Dec 13 03:32:30 CET 2004


Oops,

  Thanks for the reply, but lets try again - I was in a real rush last night...and I obviously posted the wrong code.

  I'm trying to use the __import__ form of import because I want to dynamically load classes from their .py files.  When I run the BMTest.py file, I get the error:

  File "C:\development\BMTest.py", line 10, in __init__
    tb.PrintHello()
  AttributeError: 'module' object has no attribute 'PrintHello'

  It's not recognising that BMTest2 has a PrintHello method!  The shell dir function reports this:

>>> import BMTest2
>>> dir(BMTest2)
['BMToolBar', '__builtins__', '__doc__', '__file__', '__name__', 'wx']
>>> tb = __import__('BMTest2')
>>> dir(tb)
['BMToolBar', '__builtins__', '__doc__', '__file__', '__name__', 'wx']

  Am I not defining PrintHello correctly?

  Heres the source again (the proper version this time):

**********************************
class one - BMTest - in BMTest.py:
**********************************
import wx
from traceback import print_exc
#from BMTest2 import BMToolbar

class ImportTest(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "ImportTest",
                          size = (666,480), style = wx.DEFAULT_FRAME_STYLE)
        #tb = BMToolBar(self) # works just fine!
        tb = __import__('BMTest2')
        tb.PrintHello()


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 two - BMToolBar - 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"

  Sorry for the confusion...

Bones



/
/




More information about the Python-list mailing list