Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Import Classes from Another File
-
Hello, this is probably a dumb question but I am having hard time in loading classes defined in another file (that has the same directory), into the current file. Any help would be really appreciated. Thanks!
-
I'm not sure how to do this, but you should change the topic to Question.
-
If the two files are in the same directory then you just need
import script_name
without the .py at the end.The problem that you might be seeing is that the Python Interpreter will only load a module once. So if you change an imported module then you need to force a reload(). For your own modules that you might be editing during development, I strongly recommend that you use this approach:
import import_me reload(import_me) # forces a reload of a module that has been modified
-
Hi. I tried to do what you suggested, but I still get errors that the module cannot be loaded... Can you please post an example? Thanks!
-
Running this should create a new directory containing two Python scripts that will demonstrate how one script can import another.
import datetime, os script_dict = { 'import_me' : '''import sound, time for i in xrange(7): sound.play_effect('Explosion_{}'.format(i+1)) time.sleep(0.5)''', 'importer' : 'import import_me ; reload(import_me)' } now = datetime.datetime.today().strftime('%Y_%m_%d_%H_%M_%S') dir_name = '{}_{}'.format(__file__[:-3], now) # [:-3] strips off the trailing .py os.mkdir(dir_name) for script in script_dict: with open('{}/{}.py'.format(dir_name, script), 'w') as out_file: out_file.write(script_dict[script]) print('Now run {}/importer.py'.format(dir_name.rpartition('/')[2] or dir_name))
Running importer.py will cause it to play the sounds from import_me.py. If you comment out the call to
reload()
then the sounds will not play after they have been imported once. -
Thanks for sharing the code with me. I successfully run it, but I still have problem importing classes.
Here is the file to be imported (named import_me.py):
class myclass (object): def ___init__(self): self.hi = 'say hello' def action(self): return 'hello there'
And here's my main.py file (for which I build a simple UI with a label and a button, and I link the action with the button):
import ui import import_me; reload(import_me) def buttonPressed(sender): v=sender.superview c = myclass() v['label1'].text = c.action() v = ui.load_view('main') v.present()
What am I doing wrong?
-
Replace
c = myclass()
withc = import_me.myclass()
Alternatively try
from import_me import myclass
-
worked perfectly!
-
One more caution... Your init() method starts with three underscores instead of two so it will never be called.