I have a code that I wish to split apart into multiple files. In matlab one can simply call a .m
file, and as long as it is not defined as anything in particular it
I am researching module usage in python just now and thought I would answer the question Markus asks in the comments above ("How to import variables when they are embedded in modules?") from two perspectives:
Here is how I would rewrite the main program f1.py to demonstrate variable reuse for Markus:
import f2
myStorage = f2.useMyVars(0) # initialze class and properties
for i in range(0,10):
print "Hello, "
f2.print_world()
myStorage.setMyVar(i)
f2.inc_gMyVar()
print "Display class property myVar:", myStorage.getMyVar()
print "Display global variable gMyVar:", f2.get_gMyVar()
Here is how I would rewrite the reusable module f2.py:
# Module: f2.py
# Example 1: functions to store and retrieve global variables
gMyVar = 0
def print_world():
print "World!"
def get_gMyVar():
return gMyVar # no need for global statement
def inc_gMyVar():
global gMyVar
gMyVar += 1
# Example 2: class methods to store and retrieve properties
class useMyVars(object):
def __init__(self, myVar):
self.myVar = myVar
def getMyVar(self):
return self.myVar
def setMyVar(self, myVar):
self.myVar = myVar
def print_helloWorld(self):
print "Hello, World!"
When f1.py is executed here is what the output would look like:
%run "f1.py"
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Display class property myVar: 9
Display global variable gMyVar: 10
I think the point to Markus would be: