F21SC Industrial Programming: Python: Classes and Exceptions

Similar documents
Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

dnaseq.py Introduction to Algorithms Recitation 9b October 12, 2011

LECTURE 4 Python Basics Part 3

FILE HANDLING AND EXCEPTIONS

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Exceptions CS GMU

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013

CIS192 Python Programming

CIS192 Python Programming

CIS192 Python Programming

Introduction to Python programming, II

CIS192 Python Programming

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

Overloading. F21SC Industrial Programming: Python: Advanced Language Features. Overloading. Overloading arithmetic operations

Exceptions & a Taste of Declarative Programming in SQL

Object Model Comparisons

F21SC Industrial Programming: Functional Programming in Python

Exceptions & error handling in Python 2 and Python 3

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

Introduction to Python programming, II

Object Oriented Programming

CS Programming Languages: Python

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

What we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14

Overloading. F21SC Industrial Programming: Python: Advanced Language Features. Overloading. Overloading arithmetic operations

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

381 INTRODUCTION TO PYTHON SUSHIL J. LOUIS

Lecture #12: Quick: Exceptions and SQL

Class extension and. Exception handling. Genome 559

LECTURE 6 Python Basics Part 5

CSc 120. Introduction to Computer Programming II. 07: Excep*ons. Adapted from slides by Dr. Saumya Debray

Structure and Flow. CS 3270 Chapter 5

Software Development Python (Part B)

OOP and Scripting in Python Advanced Features

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Computational Concepts Toolbox. Object Oriented Programming. Today: class. Review: Objects

Class extension and. Exception handling. Genome 559

Outline. An Application: A Binary Search Tree. 1 Chapter 7: Trees. favicon. CSI33 Data Structures

Python Tutorial. Day 2

CSI33 Data Structures

A case study of delegates and generics in C#

Introduction to python

Exception Handling. Genome 559

n 1 i = n + i = n + f(n 1)

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

CS 11 python track: lecture 2

Agenda. Excep,ons Object oriented Python Library demo: xml rpc

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

Lessons on Python Classes and Objects

Python File Modes. Mode Description. Open a file for reading. (default)

Python Interpreted language: work with an evaluator for language expressions (like DrJava, but more flexible) Dynamically typed

CSE : Python Programming

Exception Handling and Debugging

C# Data Manipulation

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

F28HS Hardware-Software Interface: Systems Programming

F21SC Industrial Programming: Python: Advanced Language Features

61A Lecture 25. Friday, October 28

Binary search trees. We can define a node in a search tree using a Python class definition as follows: class SearchTree:

61A Lecture 16. Wednesday, October 5

EXCEPTIONS, CALCULATOR 10

Introduction to Object-Oriented Programming

Python Interview Questions & Answers

Lecture 21. Programming with Subclasses

Python-2. None. Special constant that is a null value

Do not turn this page until you have received the signal to start. In the meantime, please read the instructions below carefully.

Lecture 21. Programming with Subclasses

Review 3. Exceptions and Try-Except Blocks

C# Data Manipulation

Motivation. Reflection in C# Case study: Implicit Serialisation. Using implicit serialisation. Hans-Wolfgang Loidl

Positional, keyword and default arguments

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

CS61B Lecture #7. Announcements:

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

Pairs and Lists. (cons 1 2) 1 2. (cons 2 nil) 2 nil. Not a well-formed list! 1 > (cdr x) 2 > (cons 1 (cons 2 (cons 3 (cons 4 nil)))) ( ) (Demo)

Chapter 9: Dealing with Errors

Full Python Tutorial. Python. Language features. Dynamic typing the key difference. Why Python? Introduction to Programming Languages and Techniques

Ch.7: Introduction to classes (part 2)

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

List Comprehensions. Function Definitions. This is the same as mapping the doubling function on the list [1,2,3], but without an explicit

Python iterators and generators

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

LECTURE 6. Advanced Functions and OOP

CS 11 python track: lecture 4

Sequences and iteration in Python

CNRS ANF PYTHON Objects everywhere

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

Abstract Data Types Chapter 1

Lecture 21. Programming with Subclasses

Advanced topics, part 2

At full speed with Python

pygtrie Release Jul 03, 2017

CALCULATOR Calculator COMPUTER SCIENCE 61A. July 24, 2014

APT Session 2: Python

Babu Madhav Institute of Information Technology, UTU 2015

Introduction to: Computers & Programming: Exception Handling

Transcription:

F21SC Industrial Programming: Python: Classes and Exceptions Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2017/18 0 No proprietary software has been used in producing these slides Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 1 / 30

Class definition Class definition uses familiar syntax: class ClassName (SuperClass_1,..., SuperClass_n): statement_1... statement_m Executing the class definition generates a class object, which can be referenced as ClassName. The expression statement_i generates class attributes (fields). Additionally, attributes of parent classes SuperClass_i are inherited, Class objects can be called just like functions (they are callable). Calling a class-object generates an instance of this object (no new necessary!). Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 2 / 30

Class attributes The following example generates a class with 2 attributes, one is a variable classvar1 and one is a method method1. class C: "Purpose-free demo class." classvar1 = 42 def method1 (self): "Just a random method." print ("classvar1 = %d" % C.classVar1) X = C x = X() X.method1(x) x.method1() # alias the class object # create an instance of C # call method (class view) # call method (instance view) NB: dir(c) lists all attributes of a class. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 3 / 30

Post-facto setting of class attributes A class is just a dictionary containing its attributes. Attributes can be added or modified after having created the instance (post-facto). NB: this is usually considered bad style! class D: pass # empty class object def method(self): # just a function print (D.classVar) # not-yet existing attribute print (D. dict [ classvar ]) # same effect print (self.classvar) # ditto d = D() D.method = method D.classVar = 42 d.method() # create an instance # add new class attributes # prints 42 (thrice) Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 4 / 30

Instance variables The following example defines a binary search tree: class BinTree: "Binary trees." def init (self, label, left=none, right=none): self.left = left self.label = label self.right = right def inorder(self): if self.left!= None: self.left.inorder() if self.label!= None: print (self.label) if self.right!= None: self.right.inorder() init is a constructor that initialises its instance attributes. Within a method always use a qualified access as in self.attr. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 5 / 30

Instance attributes Instance attributes can be set post-facto: x = C() x.counter = 1 while x.counter < 10: x.counter = x.counter * 2 print (x.counter) del x.counter x. class refers to the class-object of x. x. dict lists all attributes in x. dir(x) lists the namespace of x. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 6 / 30

Method objects Bound methods know the instances they are working on. >>> c = C() >>> c.method1 <bound method C.method1 of < main.c instance at >>> c.method1() Unbound methods need the instance as an additional, first argument. >>> C.method1 <unbound method C.method1> >>> C.method1(c) Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 7 / 30

Inheritance Single inheritance: class EmptyTree(BinTree): def init (self): BinTree. init (self, None) class Leaf(BinTree): def init (self, label): BinTree. init (self, label) l1 = Leaf(6) l1.printinorder() The constructor of the parent class has to be called explicitly. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 8 / 30

Inheritance Sub-classes can add attributes. class MemberTree(BinTree): def member(self, x): return bool(self.label == x or (self.left and self.left.member(x)) or (self.right and self.right.member(x))) The constructor init is inherited. Multiple inheritance is possible in Python: Using class C(C1,C2,...,Cn) class attributes are first searched for in C itself, then recursively in C1,...,Cn doing a deep search. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 9 / 30

Overloading Attributes in sub-classes can be over-loaded. In this example, if the tree is sorted, search is possible in logarithmic time: class SearchTree(MemberTree): """Ordered binary tree.""" def member(self, x): return bool(self.label == x or (self.label > x and self.left and self.left.member(x)) or (self.label < x and self.right and self.right.member(x))) Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 10 / 30

Private Variables Attributes of the form ident are local to the class (private). Internally they are renamed into the form _ClassName ident. class Bla(): privatevar = 4 def method(self): print (self. privatevar) print (self. class. dict [ _Bla privatevar ]) b = Bla() b.method() # prints 4 (twice) Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 11 / 30

: Bank Account class BankAccount: "Plain bank account." latestaccountno = 1000; # NB: this init is done too la def init (self, name, accountno = 0, balance = 0):... def Deposit(self, x): self.balance += x; def Withdraw(self, x): if self.balance >= x: self.balance -= x; else: raise InsufficientBalance, "Balance too low: %d" def ShowBalance(self): print ("Current Balance: ", self.balance); Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 12 / 30

: Bank Account class ProperBankAccount(BankAccount): """Bank account with overdraft.""" def init (self, name, accountno = 0, balance = 0):... def Withdraw(self, x): """Withdrawing money from a ProperBankAccount account if self.balance+self.overdraft >= x: self.balance -= x; else: raise InsufficientBalance, "Balance (incl overdra def ShowAccount(self): """Display details of the BankAccount.""" BankAccount.ShowAccount(self) print ("\t with an overdraft of ", self.overdraft)... Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 13 / 30

: Bank Account class Tester: """Tester class.""" def RunTrans(self,acct): """Run a sequence of transactions.""" if (isinstance(acct,properbankaccount)): # test class acct.overdraft = 200 # if ProperBan acct.showaccount(); acct.showbalance();... try: acct.withdraw(y); except InsufficientBalance: print("insufficientbalance ", acct.getbalance(), "... Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 14 / 30

: Bank Account # main: if name == main : # check whether this module is t = Tester(); # generate a tester instance # create a basic and a propoer account; NB: no new ne mine = BankAccount("MyAccount"); mineovdft = ProperBankAccount("MyProperAccount"); # put both accounts into a list; NB: polymorphic accts = [ mine, mineovdft ] # iterate over the list for acct in accts: # run transactions on the current account t.runtrans(acct) Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 15 / 30

Exceptions Exceptions can be caught using a try...except... expression. while True: try: x = int(raw_input("please enter a number: ")) break except ValueError: print ("Not a valid number. Try again...") It is possible to catch several exceptions in one except block: except (RuntimeError, TypeError, NameError): pass Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 16 / 30

Exceptions Several exception handling routines import sys try: f = open( myfile.txt ) s = f.readline() i = int(s.strip()) except IOError, (errno, strerror): print ("I/O error(%s): %s" % (errno, strerror)) except ValueError: print ("Could not convert data to an integer.") except: print ("Unexpected error:", sys.exc_info()[0]) raise Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 17 / 30

Exceptions: else If no exception was raised, the optional else block will be executed. for arg in sys.argv[1:]: try: f = open(arg, r ) except IOError: print ( cannot open, arg) else: print (arg, has, len(f.readlines()), lines ) f.close() Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 18 / 30

Raising Exceptions raise Ex[, info] triggers an exception. raise triggers the most recently caught exception again and passes it up the dynamic call hierarchy. >>> try:... raise NameError, HiThere... except NameError:... print ( An exception flew by! )... raise... An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in? NameError: HiThere Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 19 / 30

Clean-up The code in the finally block will be executed at the end of the current try block, no matter whether execution has finished successfully or raised an exception. >>> try:... raise KeyboardInterrupt... finally:... print ( Goodbye, world! )... Goodbye, world! Traceback (most recent call last): File "<stdin>", line 2, in? KeyboardInterrupt Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 20 / 30

Exceptions: All Elements Here is an example of an try constructs with all features: def divide(x, y): try: result = x / y except ZeroDivisionError: print ("division by zero!") else: print ("result is", result) finally: print ("executing finally clause") Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 21 / 30

Pre-defined clean-up with triggers automatic clean-up if an exception is raised In the example below, the file is automatically closed. with open("myfile.txt") as f: for line in f: print (line) Using with is good style, because it guarantees that there are no unnecessary, open file handles around. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 22 / 30

User-defined Exceptions The user can define a hierarchy of exceptions. Exceptions are classes, which inherit (indirectly) from the class BaseException. By default, the init method stores its arguments to args. To raise an exception, use raise Class, instance (instance is an instance of (a sub-class of) Class). Or use raise instance as a short-hand for: raise instance. class, instance Depending on context, instance can be interpreted as instance.args, e.g. print instance. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 23 / 30

User-defined Excpetions The default usage of arguments can be modified. In this example: use the attribute value instead of args. class MyError(Exception): def init (self, value): self.value = value def str (self): return repr(self.value) try: raise MyError(2*2) except MyError, e: print ( My exception occurred, value:, e.value) Together with the constructor, the representation function str needs to be modified, too. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 24 / 30

User-defined Exceptions The following code prints B, B, D (because except B also applies to the sub-class C of B. class B(BaseException): class C(B): pass class D(C): pass pass for c in [B, C, D]: try: raise c() except D: print ("D") except B: print ("B") except C: print ("C") Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 25 / 30

Iterators in detail it = iter(obj) returns an iterator for the object obj. it.next() returns the next element or raises a StopIteration exception. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 26 / 30

Do-it-yourself Iterator To define an iterable class, you have to define an iter () method, which returns the next element whenever the next() method is called. class Reverse: "Iterator for looping over sequence backwards" def init (self, data): self.data = data self.index = len(data) def iter (self): return self def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 27 / 30

Generators A method, containing a yield expression, is a generator. def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] Generators can be iterated like this. >>> for char in reverse( golf ): print (char)... f l o g Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 28 / 30

Generator Expressions Similar to list-comprehensions: >>> sum(i*i for i in range(10)) 285 >>> xvec = [10, 20, 30] >>> yvec = [7, 5, 3] >>> sum(x*y for x,y in zip(xvec, yvec)) 260 >>> unique_words = set(word for line in page for word in line.split()) Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 29 / 30

Exercises Go to the Python Online Tutor web page, www.pythontutor.com, and do the object-oriented programming exercises (OOP1, OOP2, OOP3). Implement the data structure of binary search trees, using classes, with operations for inserting and finding an element. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2017/18 30 / 30