I have multiple python files, each with different classes and methods in it. I want to execute all those files with a main function I have separately outside all of them.
Do you mean you want to import them?
import one
import two
import three
result = one.func()
instance = two.YourClass()
something = three.func()
Note that there is no "main method" in python (perhaps you've been using JAVA?). When you say python thisfile.py
, python executes all of the code in "thisfile.py". One neat little trick that we use is that each "module" has an attribute "name". the script invoked directly (e.g. thisfile.py
) gets assigned the name "__main__"
. That allows you to separate the portion of a module which is meant to be a script, and the portion which is meant to be reused elsewhere. A common use case for this is testing:
#file: thisfile.py
def func():
return 1,2,3
if __name__ == "__main__":
if func() != (1,2,3):
print "Error with func"
else:
print "func checks out OK"
Now if I run this as python thisfile.py
, it will print func checks out OK
, but if I import it in another file, e.g:
#anotherfile.py
import thisfile
and then I run that file via python anotherfile.py
, nothing will get printed.