tekion <[EMAIL PROTECTED]> writes: > Hello, > I am playing with class. Below is the code snippet: > #!/usr/bin/python > 2 > 3 class test_class: > 4 #import gzip > 5 def __init__(self,file): > 6 self.file = file > 7 def open_file(self): > 8 try: > 9 print "file: %s" % self.file > 10 self.xml_file = gzip.GzipFile(self.file,'r') > 11 except: > 12 print "an exception has occured" > 13 for line in self.xml_file: > 14 print "line: %s" % line > 15 self.xml_file.close() > 16 > 17 > 18 if __name__ == '__main__': > 19 import gzip > 20 import sys > 21 t = test_class( sys.argv[1] ) > 22 t.open_file() > > My question are: > 1. Why do I need to use "import gzip" on main section to get it the > script to work? I would assume you need the import of gzip in the > class section.
This is how Python works. Here is the relevant extract from the Reference Manual: A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes generator expressions since they are implemented using a function scope. (Quoted from http://docs.python.org/reference/executionmodel.html) > 2. What is the proper way of using module in a class you are creating? import it into the global namespace of the module in which you are defining your class. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list