csc1018f: object orientation, exceptions and file handling diving into python ch. 5&6 think like...
TRANSCRIPT
CSC1018F: Object Orientation,
Exceptions and File HandlingDiving into Python Ch. 5&6
Think Like a Comp. Scientist Ch. 11-13
Lecture Outline
Recap of Intermed Python [week 2]Object Orientation:
Module importingDefining, initializing and instantiating ClassesClass attributesClass methods
ExceptionsFile Handling:
Opening, reading, writing and closing
Recap of Intermediate Python
Basics:Conditionals (if statements)Iteration (while and for loops)
Introspection:Optional and Named ArgumentsBuilt-in FunctionsFiltering Listsand & orLambda Functions
Recap Exercise: Image Thresholding
Assume that an image is represented:With greyscale pixel values in the range 0 (black) to 255 (white) As a list of lists of integersEach sublist represents a row of pixels
Write functions to perform the following operations:
Threshold(image, threshval) - return an image which has all values below threshval converted to 0 and all those equal or above to 255. Threshval should default to 100Challenge: try and compress the body of the function into a single line
def Threshold(image, threshval = 100):
return [[(pixel < threshval and [0] or [1])[0] forpixel in row] for row in image]
Importing Modules
import moduleAllows access to methods and attributes of moduleBut requires a module.method specifier
from module import methodImports method directly into the local namespaceCan be called without a specifier
from module import *Imports all aspects of module into the local namespaceCan be dangerous with namespace conflicts
Defining and Initializing Classes
No separate class interface definition requiredAllows multiple inheritance (passed as comma-separated arguments to class)
Ancestor methods must be explicitly called
self is specified as first parameter to all class methods
Provides a reference to the class instanceNot required when calling the method
__init__ acts like a class constructor
class ClassName(Ancestor):"doc for class"__init__(self, otherparam = “default”):
Ancestor.__init__(self)
Using Classes
Import appropriatelyimport ClassFile
Class instantiated by calling it like a function passing __init__ parametersc = ClassName(initparam)
Class methods and attributes can be accessed with ‘.’ notationc.__class__c.__doc__
Class Attributes
Instance variablesData specific to an instanceQualified by instance name, e.g., instance.varBy convention initialized in __init__
Class attributesData owned by the class itself, not particular to an instanceDeclared in the class itself, usually after the doc stringAvailable directly from the class, as well as its instances, e.g., classname.attrib, instance.attribMost useful as class-level constants
Class Methods
Note: method overloading is not supported in PythonSpecial Class Methods:
Methods with a different calling syntaxExample: __len__(self) called as len(instance) Other cases __getitem__, __setitem__
Private Class Methods:Determined entirely by name (start with two underscores “__”)Not accessible outside the classSimilar notation for private functions and attributes
Handling Exceptions
Use try…except block to handle exceptions Use raise to generate exceptionsDefault behaviour is to print an error and exitBut in many cases you can anticipate exceptions
For example, trying to open a file that doesn’t exist
try:fsock = open("/notthere")
except IOError:print "The file does not exist"
else:print "File opened"
Working with File Objects
file = open(name, mode, buffering)Takes a file name and optional mode and buffering parameter, returns a file objectname and mode are useful file object attributes
file.tell()Returns the current position in an open file
file.seek(pos, mode)mode = 0, move to absolute posmode = 1, move to curr + posmode = 2, move to end - pos
File.close()Closes an open file. This can be confirmed with the boolean attribute closed
Reading and Writing
data = file.read(numbytes)Returns a string containing the read data
file.write(data)If file is opened in ‘w’ mode then data overwrites any existing file contentsIf file is opened in ‘a’ mode then data is appended to the end of the file
Also read up on sys.modules and how to work with directories
Revision Exercise
Create an image class with the following methods:
__init__ - creates a white image with a user specified x, y resolutionCheckValidity() - which checks if all pixel rows have the same lengthPadTrunc(l) - which appends white pixels to rows < length l or truncates rows > length lThreshold(t) - set all pixels <= t to 0 and the rest to 255 Resize(x, y) - alters the resolution of an image by making calls to PadTrunc and/or dropping rows