66
More Control and Expanded I/O options

More Control and Expanded I/O options

  • Upload
    elyse

  • View
    26

  • Download
    0

Embed Size (px)

DESCRIPTION

More Control and Expanded I/O options. Part 1: Defining classes. By the end of this session, you should be able to define a class, store it in a file, import it and use it in another program. self as a parameter local variables parameters and arguments special operators polymorphism. - PowerPoint PPT Presentation

Citation preview

Slide 1

More Control and Expanded I/O optionsPart 1: Defining classesBy the end of this session, you should be able to define a class, store it in a file, import it and use it in another program.self as a parameterlocal variablesparameters and argumentsspecial operatorspolymorphism

Recall from first weekA class is a definition of a category of objects and the methods that operate on those objectsA specific instance of a class is called an objectA class may be related to other classes, and inherit properties from the other class or extend the properties of another class.A class student is a subclass of personA student has all the characteristics of a person, but has other characteristics as well (perhaps major, gpa, etc.)Backward referencesWe will use examples that were introduced earlier. Look back at the previous slides and look at the book to find the details that were provided then.Examples:greatest common divisortelevision classDefining a classSimilar to defining a function, which we have done.We saw earlier that a class consists of attributes for the data and methods for operating on the data.These get translated into Python code as references to selffunctions defined on self, other parametersclass introduces a class definitionclasses can reference each other6Point Classclass Point:__init__ called the constructor. Executed when a new object is created from a class.self lets Python know that a method or data is a member of the class.For a data member it should be self._x where _x is the class data attribute. Without the self a variable is only a local variable inside a class method.For a method the self is the first parameter in the parameter list. __init__(self, . . .)This is what allows us to instantiate an instance of the class an object.7Indentation Pattern for a Class

So, this one class includes three methods (function definitions)Notice the indentation: Each function definition is indented and the body of each function is indented within the function.Creating an instance (an object) from a class__init__(self) defines the structure of the objects of this class. There are two components to objects of this class: _x and _y (yes, the _ is a significant part of the name.)When a program uses the Point class, the __init__ function establishes its parts and assigns each of the parts the value 0 in this example.

Creating a Point object:a = Point()class Point: def __init__(self): self._x = 0 self._y = 0a is now a Point object. It consists of two numbers, which we might think of as the x and y components of the Point The setX, setY methodsWe can set the value of the Point a:a = Point()a.setX(5)a.setY(2) def setX(self, val): self._x = val def setY(self, val): self._y = val_x and _y make these parameters invisible to the caller.a is now the point (using < > to avoid confusion with () and [] which already have meaning.)Referencing the components of the PointSince _x and _y are hidden, the program cannot reference a.x or a.yInstead, a.getX()a.getY()Next example uses corner instead of a as the name of the Point.11Connection Between a Method (setX) for the object corner and setX definition in the class.

12Two PerspectivesLeft part of each box: perspective from outside the Point class.Right part of each box: perspective from inside the Point class.

Parameter used to define the objectArgument used to reference the objects methods from the program13Accessors and MutatorsAccessors and mutators let users of the class access data members and change data member values.getX(self) can return the X data member.This is an accessorsetX(self, val) will change the X data member to be val.This is a mutator

14Summary: Creating a point classclass Point:def __init__(self):self._x = 0 self._y = 0

def getX(self, val):return self._x

def getY(self, val):return self._y

Point has two components, x and y, initially set to 0Point has methods that allows its x and y components to be referenced15Point Class (Continued)def setX(self, val):self._x = val

def setY(self.val):self._y = val

Point has methods that allow its x and y components to be modified.16Using the Point Class#create a new object corner of type Pointfrom SimplePoint import Pointcorner = Point() corner.setX(8) #8 is value of _x in object cornercorner.setY(6) #6 is value of _y in object corner

This assumes that we have created a file with the SimplePoint class definition.#Example SimplePoint code from Chapter 6 of textclass Point: def __init__(self): self._x = 0 self._y = 0 def __str__(self): return ' def getX(self): return self._x def setX(self, val): self._x = val def getY(self): return self._y def setY(self, val): self._y = valThis code stored in file named SimplePoint.pyfrom SimplePoint import Pointa=Point()a.setX(5)a.setY(2)b = Point()b.setX(-8)b.setY(-3)

print "a is ", a, " b is ",bThis code stored in file named class-import-test.py#Example SimplePoint code from Chapter 6 of textclass Point: def __init__(self): self._x = 0 self._y = 0 def __str__(self): return ' def getX(self): return self._x def setX(self, val): self._x = val def getY(self): return self._y def setY(self, val): self._y = valfrom SimplePoint import Pointa=Point()a.setX(5)a.setY(2)b = Point()b.setX(-8)b.setY(-3)

print "a is ", a, " b is ",bThis code stored in file named class-import-test.pyClass name matchThis code stored in file named SimplePoint.pyFile name matchclass Echo: def __init__(self, anyStr): self.text = anyStr def __str__(self): return str(self.text) + " " + str(self.text)Check PointCreate a classMake a class called EchoIt has one parameter, a stringIt uses __init__ to instantiate an object and __str__ to cast the object as a string for printing and return the string duplicated, with a space between the copies.Create a calling program to obtain a string from the user and call Echo to print it out twicevu50390:ch06 lcassel$ vu50390:ch06 lcassel$ python useecho.pyEnter your string Greetings!!Greetings!! Greetings!!vu50390:ch06 lcassel$Here is a sample run21Improved Point class#if no values are specified for x and y then#the values are set to 0.def __init__(self, initX = 0, initY = 0)self._x = initXself._y = initY

#Scales the point by a value factor.def scale(self, factor):self._x *= factorself._y *= factor22Improved Point Class (continued)def distance(self, other):dx = self._x - other._xdy = self._y other._yreturn sqrt(dx*dx + dy*dy)

#using the distance methodpoint1 = Point(5,20)point2 = Point(45,60) apartAmt = point1.distance(point2) Note this requires import math or from math import sqrt23Improved Point Class (continued)#normalize point make its distance to the #origin 1def normalize(self):mag = self.distance(Point()) #Point() creates new point at originif mag > 0: #don't scale if point is at originself.scale(1/mag)24Improved Point Class (continued)#allow print to be able to print a point object.def __str__(self):return ''

#using __str__ methodnew = Point(3, 5)print new#output

25Improved Point Class (continued)Can not use to initialize an object. point = #this is an errorCan overload most operators so that they have a new meaning when used with new objects.An example is + operator when used with int and float does addition. When used with str it does concatenation (sticks the two strings together).26Improved Point Class (continued)#overloading operators: + overloadingdef __add__(other):return Point(self._x +other._x, self._y+other._y

#using the __add__ methodnew = Point(3, 5)old = Point(4, 7)total = new + oldprint total#output

27PolymorphismOperator may do a different operation depending on the type that is passed into the operator.Multiplication operator: int or float multiply each component by the value, point do a dot product.isinstance(variable, Type) returns True if variable is of type Type.28Polymorphism#if val is an int or float it does the# if code #if a Point it does the elif code.def __mul__(self, val):if isinstance(val, (int, float)):#performs regular multiplication #operation.return Point(self._x*val, self._y*val)elif isinstance(val, Point):#performs dot product operation.return self._x*val._x + self._y*val._y Spot CheckDo exercise 6.4 in the text. Enter the code shown.Execute each of the examplesExplain the resultsOther examplesLook at the descriptions of the Television and Fraction classes in the text for further examples of class definition.More control Catching exceptions32Exceptions: How to Deal with Error Situationsnumber = 0while not 1 >> rank = 5>>> print team, ": ranked", rank, "this week."Wildcats : ranked 5 this week.>>> >>> print team+": ranked " + str(rank) +" this week."Wildcats: ranked 5 this week.Formatting StringsFurther control of how individual fields of output will be presented.% is used to indicate a formatting code and also a tuple of items to be formatted%s for strings%d for integers (d for digits?)%f for floats (numbers with decimal parts)%.3f displays three decimal places

41Formatted Strings (continued)Can write previous statement using formatting strings like this.

Format strings are:%s is for strings%d is for integers%f is for floats. %.2f gives two decimal places.>>> print '%s: ranked %d this week.'%(team, rank)Wildcats: ranked 5 this week.Notice quotes around the whole specification of the formatting.Formatting detailsFurther options%10s -- string with 10 spaces, minimum%4d -- number with 4 spaces, minimum-%5.2f -- float with 5 places, of which two are decimal positions

>>> print 'Rank %5.2f as a float.'%rankRank 5.00 as a float.>>> print 'Rank %10.2f as a float.'%rankRank 5.00 as a float.

>>> rank = 100 >>> print "Rank %3.2f with field too small"%rankRank 100.00 with field too smallNote: %n.df makes the total columns for the number =n, of which d are for the decimal places%3.2f means total 3 spaces, one is for the decimal point and two for the decimal digits, none for the whole number. Automatically expanded to fit the actual value.Short spot checkWrite code to print out Today is 10 October 2012Where the date consists of 3 variablesDay is an integerMonth is a stringYear is an integerUse the formatting tools we just saw and make the day number always 2 digits, the month name a set length (long enough for any month) and the year four digits.44Working with FilesInformation stored in RAM (main memory) goes away (is volatile) when the computer is shut off.Information stored on disk is non-volatile (does not go away when the computer is turned off).Writing to and reading from a file can help preserve information between different executions of a program. 45Python File Typecreating a new file instance is accomplished in the same way that a new list object is made.

fileObj = file(filename)

46File OperationsSyntaxSemanticsclose()disconnect file from Python file variable and save file.flush()flushes buffer of written characters.read()returns a string with remaining contents of the file.read(size)returns a string with size bytes remaining in file.readline()returns string that contains next line in the file.47File Operations (continued)SyntaxSemanticsreadlines()returns a list of strings of the remaining lines in the file.write(s)writes s to the file. No newlines are added.writelines(seq)writes the lines in seq to the file.for line in f:iterates through the line f, one line at a time. 48Reading from a File:Counting lines, words, and charactersversion 1 corrected typos and added formattingfilename = raw_input('What is the filename? ')source = file(filename)text = source.read() # Read entire file as one stringnumchars = len(text)numwords = len(text.split())numlines = len(text.split('\n'))print '%10d Lines\n%10d Words\n%10d Characters'%(numlines,numwords,numchars)source.close()What is the filename? citeseertermcount.txt 30002 Lines 156521 Words 920255 CharactersNote this version reads the whole file at once, as a single string49Reading from a File:Counting lines, words, and characters version 2numlines=numwords=numchars=0line=source.readline()while line: # line length is not zero numchars+=len(line) numwords +=len(line.split()) numlines+=1 # Done with current line. Read the next line=source.readline()

print '%10d Lines\n%10d Words\n%10d Characters'%(numlines,numwords,numchars)source.close()Now, we read one line at a time, process it, and read the next.What is the filename? citeseertermcount.txt 30001 Lines 156521 Words 920255 CharactersNote different number of lines50Reading from a File:Counting lines, words, and characters version 3filename = raw_input('What is the filename? ')source = file(filename)numlines = numwords = numchars = 0for line in source: #reads one line at a time until no more. numchars += len(line) numwords += len(line.split()) numlines += 1

print '%10d Lines\n%10d Words\n%10d Characters'%(numlines,numwords,numchars)source.close() 30001 Lines156521 Words920255 CharactersNote that for line in source actually does the read of a line. No explicit readline is used.Note the number of linesSpot check Read a file of your choice anything you have is fineFind the longest lineOutput the line number and its length in characters52Writing to a FileCreating a new file object that can be written to in Python with a file name of filename. result = file(filename, 'w')If the file with filename already exists then it will be overwritten.Only strings can be written to a filepi = 3.14159result.write(pi) #this is illegalresult.write(str(pi)) #this is legal53Writing to a FileWhen is the information actually written to a file?File writing is time expensive so files may not be written immediately.A file can be forced to be written in two ways:flush(): file written but not closed.close(): file written and then closed.File Write DangerNote that there is no built-in protection against destroying a file that already exists! If you want to safeguard against accidentally overwriting an existing file, what would you do?Discuss55Trying to Read a File That Doesn't Exist.What if opening file for reading and no file with that name exists? IOError crashes program. To avoid this use an exception.

filename = raw_input('Enter filename: ')try: source = file(filename)except IOError: print 'Sorry, unable to open file', \ filename56File Utilities# Prompt for filename until file is successfully opened.def fileReadRobust(): source = None while not source:filename = raw_input('Input filename: ')try: source = file(filename)except IOError: print 'Sorry, unable to open file', filenamereturn source57File Utilities (continued)def openFileWriteRobust(defaultName): """Repeatedly prompt user for filename until successfully opening with write access. Return a newly open file object with write access. defaultName a suggested filename. This will be offered within the prompt and used when the return key is pressed without specifying another name. """ writable = None while not writable: # still no successfully opened file prompt = 'What should the output be named [%s]? '% defaultName filename = raw_input(prompt) if not filename: # user gave blank response filename = defaultName # try the suggested default try: writable = file(filename, 'w') except IOError: print 'Sorry. Unable to write to file', filename return writableSpot checkEnter the code shown for the robust file open. Add a call to this function.How can you test this code?def openFileWriteRobust(defaultName): """Repeatedly prompt user for filename until successfully opening with write access. Return a newly open file object with write access. defaultName a suggested filename. This will be offered within the prompt and used when the return key is pressed without specifying another name. """ writable = None while not writable: # still no successfully opened file prompt = 'What should the output be named [%s]? '% defaultName filename = raw_input(prompt) if not filename: # user gave blank response filename = defaultName # try the suggested default try: writable = file(filename, 'w') except IOError: print 'Sorry. Unable to write to file', filename return writable

Default="Anon"source = openFileWriteRobust(Default)print 'File open result:', source58Testing the File Utilitiesfrom FileUtilities import *

sourceFile=openFileReadRobust()if sourceFile None: print "Successful read of ",sourceFile

filenone="anyname"outFile=openFileWriteRobust(filenone)if outFile None: print "File ", outFile, " opened for writing" What is the filename? citeseertermcount.txtSuccessful read of What should the output be named [anyname]? abc.txtFile opened for writingNumbering lines in a file# Program: annotate.py# Authors: Michael H. Goldwasser# David Letscher## This example is discussed in Chapter 8 of the book# Object-Oriented Programming in Python#from FileUtilities import openFileReadRobust, openFileWriteRobust

print 'This program annotates a file, by adding'print 'Line numbers to the left of each line.\n'

source = openFileReadRobust()annotated = openFileWriteRobust('annotated.txt')

# process the filelinenum = 1for line in source: annotated.write('%4d %s' % (linenum, line) ) linenum += 1source.close()annotated.close()print 'The annotation is complete.'61Running the annotation programFileUtilities.pycciteseertermcount.txtreadfile1.pyabc.txtfileUtilTest.pyreadfile2.pyannotate.pyfileUtilities.pyreadfile3.pyannotatedUtilities.txtreadexception.pyThis program annotates a file, by addingLine numbers to the left of each line.

What is the filename? fileUtilities.pyWhat should the output be named [annotated.txt]? annotatedUtilities.txtThe annotation is complete.Directory after the program runs:The annotated file 1 # Program: FileUtilities.py 2 # Authors: Michael H. Goldwasser 3 # David Letscher 4 # 5 # This example is discussed in Chapter 8 of the book 6 # Object-Oriented Programming in Python 7 # 8 """A few utility functions for opening files.""" 9 def openFileReadRobust(): 10 """Repeatedly prompt user for filename until successfully opening with read access. 11 12 Return the newly open file object. 13 """ 14 source = None 15 while not source: # still no successfully opened file 16 filename = raw_input('What is the filename? ') 17 try: 18 source = file(filename) 19 except IOError: 20 print 'Sorry. Unable to open file', filename 21 return source 22 23 def openFileWriteRobust(defaultName): 24 """Repeatedly prompt user for filename until successfully opening with write access. 25 26 Return a newly open file object with write access.Rest not shown for space limitationsSpot Check 2Run the annotate program against a file of your choosing and get the line numbers added.Be careful not to overwrite the original file.Modify the code to remove the file numbers from the fileTally Read through the case study of constructing a tally sheet class.

Compare what you see here to the frequency distribution content that you saw in the NLTK book.NLTK chapter 3That is written very much as a tutorial and I dont think I can do much with slides and no narration.Please read through that chapter and do the Your turn exercises. Use the Discussion board to comment on what you do and to share observations and ask questions.AssignmentIn Two weeks:Do either exercise 8.18 or exercise 8.21(Do you prefer to work with numbers or words?)Be sure to design good test cases for your program.For chapter review (and quiz preparation) be sure you can do exercises 8.7 8.9