usage of __import__ across two files

bwobbones bwobbones at
Mon Dec 13 03:32:30 CET 2004


  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 file, I get the error:

  File "C:\development\", line 10, in __init__
  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
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')

class MyApp(wx.App):
    def __init__(self, flag):
        wx.App.__init__(self, flag)
    def OnInit(self):
        frame = ImportTest()
        return True
if __name__ == '__main__':
       app = MyApp(False)
       print print_exc()

class two - BMToolBar - in

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 ***"
    def PrintHello(self):
        print "Hello"

  Sorry for the confusion...



More information about the Python-list mailing list