# Define a class class SomeClass: def __init__(self, arg0): self.classMemberVar0 = arg0 print ('In __init__(), constructing a SomeClass object with classMemberVar0 == ' + \ self.classMemberVar0) # Create a function that is global to this module def MyGlobalFunction(arg0): print 'In MyGlobalFunction, arg0 has the value ' + str(arg0) localVariabletoMyGlobalFunction = 333 print 'In MyGlobalFunction, localVariabletoMyGlobalFunction has the value ' + \ str(localVariabletoMyGlobalFunction) # define a variable global to the entire module moduleGlobalVar = 222 if True: # an if statement that will always be executed # define another variable to the entire module here. Even though we are inside an 'if' # block, code blocks like this ('for' blocks are another example) do not restrict scope. # So, moduleGlobalVar and anotherModuleGlobalVar have the same scope. anotherModuleGlobalVar = 444 # Make an object sc of SomeClass sc = SomeClass('jim') # We can see values of class member variables outside of the class if we refer to the object # that the variable belongs to. If we had more than one object of this class, then the same # member variable could have different values within each object. print 'From main, I can see that sc.classMemberVar0 has the value ' + str(sc.classMemberVar0) # Call MyGlobalFunction MyGlobalFunction('fred') # Uncommenting the 2 lines in print below creates an error because localVariabletoMyGlobalFunction is not # defined in the current scope. Even though we passed 'fred' as an argument that ended up being # assigned to localVariabletoMyGlobalFunction, we cannot 'see' that variable here--it's out of scope # print 'If I try to print the value of localVariabletoMyGlobalFunction from main, I get ' + \ # str(localVariabletoMyGlobalFunction) print 'outside of if __name__, I can see that the value of anotherModuleGlobalVar is ' + \ str(anotherModuleGlobalVar) + 'even though it was defined in an if block that I am external to' # Create a for loop. Like an if statement, the block of code attached to a for loop does not further # restrict scope. So, the value of fred is visible outside the loop. for i in range (0,5): fred = 'my name is fred' pass print 'Outside of the for loop, we can see that fred has the value of ' + fred