Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch. 11-13.

Similar presentations


Presentation on theme: "CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch. 11-13."— Presentation transcript:

1 CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch. 11-13

2 Lecture Outline Recap of Intermed Python [week 2] Object Orientation: Module importing Defining, initializing and instantiating Classes Class attributes Class methods Exceptions File Handling: Opening, reading, writing and closing

3 Recap of Intermediate Python Basics: Conditionals ( if statements) Iteration ( while and for loops) Introspection: Optional and Named Arguments Built-in Functions Filtering Lists and & or Lambda Functions

4 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 integers Each 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 100 Challenge: 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] for pixel in row] for row in image]

5 Importing Modules import module Allows access to methods and attributes of module But requires a module.method specifier from module import method Imports method directly into the local namespace Can be called without a specifier from module import * Imports all aspects of module into the local namespace Can be dangerous with namespace conflicts

6 Defining and Initializing Classes No separate class interface definition required Allows 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 instance Not required when calling the method __init__ acts like a class constructor class ClassName(Ancestor): "doc for class" __init__(self, otherparam = “default”): Ancestor.__init__(self)

7 Using Classes Import appropriately import ClassFile Class instantiated by calling it like a function passing __init__ parameters c = ClassName(initparam) Class methods and attributes can be accessed with ‘.’ notation c.__class__ c.__doc__

8 Class Attributes Instance variables Data specific to an instance Qualified by instance name, e.g., instance.var By convention initialized in __init__ Class attributes Data owned by the class itself, not particular to an instance Declared in the class itself, usually after the doc string Available directly from the class, as well as its instances, e.g., classname.attrib, instance.attrib Most useful as class-level constants

9 Class Methods Note: method overloading is not supported in Python Special Class Methods: Methods with a different calling syntax Example: __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 class Similar notation for private functions and attributes

10 Handling Exceptions Use try…except block to handle exceptions Use raise to generate exceptions Default behaviour is to print an error and exit But 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"

11 Working with File Objects file = open(name, mode, buffering) Takes a file name and optional mode and buffering parameter, returns a file object name 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 pos mode = 1, move to curr + pos mode = 2, move to end - pos File.close() Closes an open file. This can be confirmed with the boolean attribute closed

12 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 contents If 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

13 Revision Exercise Create an image class with the following methods: __init__ - creates a white image with a user specified x, y resolution CheckValidity() - which checks if all pixel rows have the same length PadTrunc(l) - which appends white pixels to rows length l Threshold(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


Download ppt "CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch. 11-13."

Similar presentations


Ads by Google