Recitation 6 Programming for Engineers in Python.

Slides:



Advertisements
Similar presentations
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Advertisements

CMPT 120 Functions and Decomposition
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
 2002 Prentice Hall. All rights reserved. 1 Chapter 8 – Customizing Classes Outline 8.1 Introduction 8.2 Customizing String Representation: Method __str__.
Introduction to Python
Old MacDonald.
Classes 2 COMPSCI 105 S Principles of Computer Science.
Recitation 1 Programming for Engineers in Python.
Exceptions COMPSCI 105 S Principles of Computer Science.
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
Classes 3 COMPSCI 105 S Principles of Computer Science.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
Python Programming Chapter 14: Classes and Methods Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Object-oriented Programming (review + a few new tidbits) "Python Programming for the Absolute Beginner, 3 rd ed." Chapters 8 & 9 Python 3.2 reference.
PYTHON CONDITIONALS AND RECURSION : CHAPTER 5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Interfaces. –An interface describes a set of methods: no constructors no instance variables –The interface must be implemented by some class. 646 java.
Old macdonald had a farm
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.
Built-in Data Structures in Python An Introduction.
Functions Chapter 4 Python for Informatics: Exploring Information
Variables, Expressions, and Statements
Introduction to OOP OOP = Object-Oriented Programming OOP is very simple in python but also powerful What is an object? data structure, and functions (methods)
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Python Conditionals chapter 5
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Lecture 09 – Classes.  At the end of this lecture, students should be able to:  Define a new class  Store state information about instances of the.
Chapter 17 Q and A Victor Norman, et al. CS104. What is Object-oriented Programming? Q: What is object-oriented programming? A: It means defining classes/objects,
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 4 Python Basics Part 3.
Python Exceptions and bug handling Peter Wad Sackett.
Q and A for Sections 6.2, 6.3 Victor Norman CS106.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Exceptions in Python Error Handling.
COMPSCI 107 Computer Science Fundamentals
George Mason University
Classes and Objects – digging deeper
COMPSCI 107 Computer Science Fundamentals
Example: Vehicles What attributes do objects of Sedan have?
Mathematical operators overload
Presented By S.Yamuna AP/IT
Python - Functions.
Introduction to Object-Oriented Programming (OOP)
Topics Introduction to File Input and Output
Introduction to Object-Oriented Programming (OOP) II
Python’s Errors and Exceptions
Introduction to Object-Oriented Programming (OOP)
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Margaret Derrington KCL Easter 2014
CSC1018F: Object Orientation, Exceptions and File Handling (Tutorial)
By Ryan Christen Errors and Exceptions.
Lecture 18 Python OOP.
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Topics Introduction to File Input and Output
Introduction to Object-Oriented Programming (OOP)
Introduction to Object-Oriented Programming (OOP) II
Unit Testing.
Presentation transcript:

Recitation 6 Programming for Engineers in Python

Agenda Object Oriented Programming: Old McDonald Had a Farm Time Class 2

Example – Old McDonald 3 __str__ - Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object:

Animal class 4 class Animal: def __init__(self, name, noise): self.name = name self.noise = noise

Farm class 5 class Farm: def __init__(self): self.animals = [] def add(self, animal): self.animals.append(animal)

Farm class 6 def __str__(self): s = “” for animal in self.animals: s += 'Old MacDonald had a farm, EE-I-EE-I-O,\n' s += 'And on that farm he had a '+animal.name+', EE-I-EE-I-O,\n' s += 'With a '+ animal.noise + animal.noise+' here and a ‘ s += animal.noise + animal.noise +' there\n' s += 'Here a '+ animal.noise +', there a ‘ s += animal.noise + ', everywhere a ‘ + animal.noise s += animal.noise + '\n' s += 'Old MacDonald had a farm, EE-I-EE-I-O.\n‘ return s

Sing the song! 7 >>> farm = Farm() >>> farm.add(Animal('cow','moo')) >>> print farm Old MacDonald had a farm, EE-I-EE-I-O, And on that farm he had a cow, EE-I-EE-I-O, With a moomoo here and a moomoo there Here a moo, there a moo, everywhere a moomoo Old MacDonald had a farm, EE-I-EE-I-O. >>> farm.add(Animal('duck','kwak')) >>> farm.add(Animal('dog','woof')) >>> farm.add(Animal('cat','miaoo'))

Sing the song! 8 >>> print farm Old MacDonald had a farm, EE-I-EE-I-O, And on that farm he had a cow, EE-I-EE-I-O, With a moomoo here and a moomoo there Here a moo, there a moo, everywhere a moomoo Old MacDonald had a farm, EE-I-EE-I-O, And on that farm he had a duck, EE-I-EE-I-O, With a kwakkwak here and a kwakkwak there Here a kwak, there a kwak, everywhere a kwakkwak Old MacDonald had a farm, EE-I-EE-I-O, And on that farm he had a dog, EE-I-EE-I-O, With a woofwoof here and a woofwoof there Here a woof, there a woof, everywhere a woofwoof Old MacDonald had a farm, EE-I-EE-I-O, And on that farm he had a cat, EE-I-EE-I-O, With a miaoomiaoo here and a miaoomiaoo there Here a miaoo, there a miaoo, everywhere a miaoomiaoo Old MacDonald had a farm, EE-I-EE-I-O.

A Time class 9 We’ll define a class called Time that records the time of day (The “Think Python” Book, ch. 16 & 17): class Time(object): """represents the time of day. attributes: hour, minute, second""“ def __init__(self, hour, minute, second): self.hour = hour self.minute = minute self.second = second >>> time = Time(11, 9, 30)

Time class – cont. 10 >>> time = Time(11, 59, 30) How would we print a Time instance? def __str__(self): return "%.2d:%.2d:%.2d" % (self.hour, self.minute, self.second) >>> print time 11:59:30 >>> time.hour = 0 >>> print time 00:59:30 String formatting: seq-strings.html seq-strings.html

Time class – cont. 11 We want to add times – for example, it’s 16:00:00 and I have a meeting in 2 hours: 16:00: :00:00 = 18:00:00 def __add__(self, other): hour = self.hour+other.hour minute = self.minute+other.minute second = self.second+other.second return Time(hour, minute, second) Is this right? What will happen when adding 16:00:00 to 16:00:00?

Adding times – cont ≤hour<24, 0≤minute<60, 0≤second< minutes = 1 hour 40 minutes def __add__(self, other): hour = self.hour + other.hour minute = self.minute + other.minute second = self.second + other.second minute += second / 60 second = second % 60 hour += minute / 60 minute = minute % 60 hour = hour % 24 return Time(hour, minute, second)

Adding times – cont. 13 >>> t1 = Time(16,0,0) >>> t2 = Time(2,0,0) >>> print t1+t2 18:00:00 >>> print t1+t1 08:00:00

Subtracting times 14 Just like addition: def __sub__(self, other): hour = self.hour - other.hour minute = self.minute - other.minute second = self.second - other.second minute += second / 60 second = second % 60 hour += minute/60 minute = minute % 60 hour = hour % 24 return Time(hour, minute, second)

Even better 15 def __init__(self, hour, minute, second): minute = minute + second / 60 hour = hour + minute / 60 self.hour = hour % 24 self.minute = minute % 60 self.second = second % 60 def __add__(self, other): hour = this.hour + other.hour minute = this.minute + other.minute second = this.second + other.second return Time(hour, minute, second)

Debugging 16 We want to write a method that verifies that a Time instance is valid: def valid(self): if self.hour < 0 or self.minute < 0 or self.second < 0: return False if self.hour>=24 or self.minute >= 60 or self.second >= 60: return False return True

Exceptions 17 When the program reaches a state it can’t handle or an error it cannot recover from, it raises an exception. This means it sends an error to the user There are different types of errors. Examples: IndexError ZeroDivisionError ValueError TypeError … Full list:

Debugging – cont. 18 We want to verify that a time is valid before using it and raise an exception if a time is invalid: def __add__(self,other): if not self.valid() or not other.valid(): raise ValueError(‘invalid Time object in addition’) …. This will help us find errors and alert users of the code on wrong usage Optional: This can also be written using assert: def __add__(self,other): assert self.valid() and other.valid() ….

Comparing Time instances 19 We’d like to be able to compare times. Right now: >>> t1 = Time(16,0,0) >>> t2 = Time(5,0,0) >>> t1>t2 False >>> t1 = Time(16,0,0) >>> t1>t2 True This happens because python compares the addresses!

Comparing Time instances – cont. 20 We’d like to be able to compare times: def __cmp__(self, other): tup1 = (self.hour, self.minute, self.second) tup2 = (other.hour, other.minute, other.second) return cmp(tup1, tup2) >>> Time(16,0,0)>Time(11,30,0) True >>> Time(16,0,0)>Time(16,0,1) False

Object representation 21 >>> t1 = Time(16,0,0) >>> print t1 # calls __str__ 16:00:00 >>> t1 If we want a different output we must override the __repr__ method

Object representation – cont. 22 def __repr__(self): return self.__class__.__name__+" instance: "+self.__str__() >>> t = Time(16,0,0) >>> t Time instance: 16:00:00 Note the use of these attributes: >>> cls = t.__class__ >>> cls >>> cls.__name__ Time

Time as number of seconds 23 We note that the time of day can also be denoted by the number of seconds since the beginning of the day: def to_seconds(self): return self.hour* self.minute*60 + self.second >>> time = Time(16,0,0) >>> time.to_seconds() 5760 We already have the other direction from __init__ (see here)see here

Time as number of seconds – cont. 24 This also simplifies the _add__ and __sub__ methods: def __add__(self, other): secs = self.to_seconds() + other.to_seconds() return Time(0,0, secs) def __sub__(self,other): secs = self.to_seconds() - other.to_seconds() return Time(0,0, secs)

Comparing is also easier 25 We can also change __cmp__: def __cmp__(self, other): return cmp(self.to_seconds(), other.to_seconds()) >>> t1 = Time(16,0,0) >>> t2 = Time(21,0,0) >>> t1>t2 False

Type checking, adding integers 26 The next step is to allow __add__ to add either seconds or Time def __add__(self, other): secs = self.to_seconds() if isinstance(other, Time):# is other a Time? secs += other.to_seconds() elif isinstance(other, int):# is other an int? secs += other return Time(0,0,secs) # creating a new time

Type checking, adding integers 27 Now we can use the + operator with either int or Time: >>> time = Time(16,0,0) >>> print time+60 16:01:00 >>> print time+Time(0,1,0) 16:01:00

Type checking, adding integers 28 What if we add a float? Let’s change the if-else: def __add__(self, other): secs = self.to_seconds() if isinstance(other,Time): secs += other.to_seconds() elif isinstance(other,int): secs += other else: raise TypeError("Can't add Time and “ +other.__class__.__name__) return Time(0,0,secs)

Type checking, adding integers 29 >>> time Traceback (most recent call last): File " ", line 1, in t1+5. File "C:/python_course/Time.py", line 38, in __add__ raise TypeError("Can't add Time and "+other.__class__.__name__) TypeError: Can't add Time and float

Right-side addition 30 >>> print time :01:00 >>> print 60 + time Traceback (most recent call last): File " ", line 1, in 60 + time TypeError: unsupported operand type(s) for +: 'int' and 'Time‘ We need to implement __radd__!

Right-side addition – cont. 31 def __radd__(self,other): return self.__add__(other) >>> print 60 + time 16:01:00 Alternatively we can write: def __radd__(self,other): return self+other

The benefits of overriding + 32 We can use the built-in sum: >>> sum([Time(1,0,1),Time(2,0,2), Time(3,0,3)]) Time instance: 06:00:06

Home work 6: Point class 33 We will write a class for a Point - 2-D vector Operator overloading: All instructions in hw6.pdf Use what we learned: class Rational class Time