exceptions and making our own classes many slides from this class are from those provided with the...
Post on 26-Dec-2015
219 Views
Preview:
TRANSCRIPT
Exceptions and Making our own classes
Many slides from this class are from those provided with the text, created by Terry Scott, University of Northern Colorado. However, I will annotate most of them and add others as needed.
2
Exceptions: How to Deal with Error Situations
number = 0while not 1 <= number <= 10: try: number= int(raw_input('Enter number from 1 to 10: '))
if not 1 <= number <= 10:print 'Your number must be from 1 to 10:'
except ValueError: print 'That is not a valid integer.'
Here: recognize an error condition and deal with itIf the named error occurs, the “except” clause is executed and the loop is terminated.
book slide
3
Exceptions (continued)
• What if a negative is entered for square root?
• Can raise an exception when something unusual occurs.
def sqrE(number): if number < 0: raise ValueError('number must be positive') #do square root code as before
Note: ValueError is an existing, defined error classbook slide
4
Exceptions (continued)
#What if value entered is not a number?def sqrtF(number): if not isinstance(number, (int, float)):
raise TypeError('number must be numeric') if number < 0: raise ValueError('number must be positive') #do square root code as before
book slide
5
How Much Type Checking is Enough?
• A function with little type checking of its parameters may be difficult to diagnose errors.
• A function with much type checking of its parameters will be harder to write and consume more time executing.
• If the function is one that only you will use you may need less type checking.
• A function written for others should have more type checking.
book slide
6
Spot check on Exceptions• In pairs, write python code to do the
following:– Accept input from the keyboard
• Prompt with instructions to enter a number, and to enter some character you choose to end
– Verify that the value read is numeric– Calculate the minimum, maximum and average
of the values read– Terminate reading when a non numeric
character is entered– Print out the values calculated
Online class• This is an online class. My travel is not allowing
me to do voice-overs of the slides, so I will have to put all my comments into the slides themselves.
• Also, because the travel includes all day meetings, including dinner sessions, I don’t have the time to construct very many original slides. I have read the text chapter, will do some slides to provide an overview of the chapter, and rely on the slides provided with the book for most of the content.
• I will try to test all the code, because there have been errors in slides I used previously.
Overview• This class is about object-oriented programming, in
Python.– We focus on the Python parts a lot– This chapter is very much about the object orientation.
• At the beginning, we described classes and objects.• Along the way, we have seen built-in functions, and
have learned to create our own functions• We have imported modules, such as math• Last week, in exploring the nltk, we learned to work
with a large collection of custom materials designed for natural language processing.
• Now, we will see how to extend Python to meet our specific needs, by defining our own classes.
Mechanics • I will embed spot checks and other
questions in the slides. • You may expect that next week’s quiz
will include some of those questions and exercises, or things that are very closely patterned on these. Skip them at your peril!
Recall from first week• A class is a definition of a category of objects
and the methods that operate on those objects– A specific instance of a class is called an object
• A 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 person
• A student has all the characteristics of a person, but has other characteristics as well (perhaps major, gpa, etc.)
Backward references• We 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 divisor– television class
This class session• 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
• All the ideas will be introduced briefly, then explained by way of examples
Defining a class• Similar 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 self• functions defined on self, other parameters
• class introduces a class definition– classes can reference each other
14
Point Class
• class 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.
15
Indentation Pattern for a ClassSo, 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 = 0
a 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 methods
• We 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 <5,2>(using < > to avoid confusion with () and [] which already have meaning.)
Referencing the components of the Point
• Since _x and _y are hidden, the program cannot reference – a.x or a.y
• Instead, – a.getX()– a.getY()
Next example uses corner instead of a as the name of the Point.
19
Connection Between a Method (setX) for the object corner and setX
definition in the class.
20
Two Perspectives
• Left 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 object
Argument used to reference the object’s methods from the program
21
Accessors and Mutators
• Accessors 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 accessor
• setX(self, val) will change the X data member to be val.– This is a mutator
22
Summary: Creating a point class
class Point:def __init__(self):
self._x = 0 self._y = 0
def getX(self, val):return self._x
23
Point Class (Continued)def setX(self, val):
self._x = val
def setY(self.val):self._y = val
def setY(self, val):self._y = val
24
Using 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 '<'+str(self._x)+','+str(self._y)+'>’ 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 = val
This code stored in file named SimplePoint.py
from SimplePoint import Pointa=Point()a.setX(5)a.setY(2)b = Point()b.setX(-8)b.setY(-3)
print "a is ", a, " b is ",b
This 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 '<'+str(self._x)+','+str(self._y)+'>’ 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 = val from SimplePoint import Point
a=Point()a.setX(5)a.setY(2)b = Point()b.setX(-8)b.setY(-3)
print "a is ", a, " b is ",b
This code stored in file named class-import-test.py
Class name match
This code stored in file named SimplePoint.py
File name match
Check Point• Create a class– Make a class called Echo– It has one parameter, a string– It 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 twice
vu50390:ch06 lcassel$ vu50390:ch06 lcassel$ python useecho.pyEnter your string Greetings!!Greetings!! Greetings!!vu50390:ch06 lcassel$
Here is a sample run
28
Improved 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 *= factor
29
Improved 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 sqrt
30
Improved 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 origin
self.scale(1/mag)
31
Improved Point Class (continued)#allow print to be able to print a point object.def __str__(self):
return '<'+str(self._x)+', '+str(self._y)+ '>'
#using __str__ methodnew = Point(3, 5)print new#output<3, 5>
32
Improved Point Class (continued)
• Can not use <3,5> to initialize an object. point = <3,5> #this is an error
• Can 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).
33
Improved 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<7, 12>
34
Polymorphism• Operator 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.
35
Polymorphism#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 Check• Do exercise 6.4 in the text. Use the
Discussion Board in Blackboard to discuss the question with others in the class.
37
Television Class• Create a user class to emulate the way
television controls work.• General principles– On-off and mute are both toggle switches– All controls only work when the TV is on.– Volume control goes from1 to 10 inclusive.– Channels range from 2 – 99 inclusive. It
wraps around.– Can change channel by entering a channel
number.
38
Television Class#initializes television objectclass Television:
def __init__(self):self._powerOn = Falseself.muted = Falseself._volume = 5self._channel = 2self._prevChan = 2
39
Television Class Diagram
40
Television Class (continued)
#Clicking flips if on then off and off then ondef togglePower(self):
self._powerOn = not self._powerOn
#Clicking flips between muted and unmuted.def toggleMute(self):
if self._powerOn:self._muted = not self._muted
41
Television Class (continued)#volume can range from 1 upto including 10def volumeUp(self):
if self._powerOn:if self._volume < 10: self._volume += 1self._muted = Falsereturn self_volume #volume is
#displayed on tv when it is changed.
42
Television Class (continued)#channel increases by one and wraps back to 2def channelUp(self): if self._powerOn:
self._prevChan = self._channelif self._channel == 99: self._channel = 2else: self._channel += 1return self._channel
43
Television Class (continued)• volumeDown is similar to volumeUp just
replace test self._volume < 10 with self._volume > 1 and replace self._volume += 1 with self._volume -= 1
• channelDown is similar to channelUp just replace test self._channel == 99 with self._channel == 2 and replace self._channel += 1 with self._channel -= 1.
44
Television Class (continued)#Channel is set to number.def setChannel(self, number): if self._powerOn:
if 2 <= number <= 99: self._prevChan = self._channel
self._channel = number return self._channel
45
Trace of setChannel(7) Tuned to Channel 5 and Was Previously on
Channel 2
46
Television Class (continued)#Flip to previous channel.def jumpPrevChannel(self): if self._powerOn: incoming = self._channel
self._channel = self._prevChan self._prevChan = incoming return self._channel
47
Flawed Swap of Channels
#Left picture is starting situationself._channel = self._prevChanself._prevChan = self._channel#both variables end up at 5
48
One Way to Do This in Pythonself._channel, self._prevChan=self.prevChan,self._channel
49
Television Class (continued)# previous code#using swap from previous slideincoming = self._channelself._channel = self._prevChanself._prevChan = incoming# in Python can do the following: can assign#simultaneously so no need to set to a#tempory value.self._channel,
self._prevChan=self.prevChan,self._channel
Check Point• Practice Problem 6.5 in the text.• Again, use the Blackboard discussion
board to work with classmates to solve this and to explore any questions that arise.
51
Fraction Class• Fraction consists of two numbers: a numerator
and a denominator.• Must be in lowest terms.• Denominator must be non-negative.• Denominator must be non-zero.• Method types:– constructor.– arithmetic operators.– comparison operators.– type conversion operators.
52
Fraction Class Codedef __init__(self, numer=0, denom= 0): if denom == 0: self._num = 0 self._den = 0 else: factor = gcd(abs(numer), abs(denom))
if denom < 0: factor = -factor
self._num = numer // factor self._den = denom // factor
53
Fraction Class Code (continued)
#overloads + operator for fraction objects.def __add__(self, other): return Fraction(self._num*other._den +
self._den*other._num, self._den*other._den)
#overload < operator for fraction objects.def __lt__(self, other):
return self._num*other._den<self._den*other._num
54
Fraction Class Code (continued)
# Overloads == operator for fraction objectsdef __eq__(self, other): return self._num == other._num and self._den == other._den# Overloads float operator for fraction objectdef __float__(self): return float(self._num) / self._den
55
Fraction Class Code (continued)# overloads int functiondef __init__(self): return int(float(self))# overload str functiondef __str__(self):
if self._den == 0: return 'undefined'
elif self._den == 1 return str(self._num)
else: return str(self._num) + '/' + str(self._den)
56
Complete Fraction Class from gcd import gcdclass Fraction: def __init__(self, . . .)
#include constructor code def __add__(self, . . .) #include + operator code def __sub__(self, . . .):
#similar to __add__ code just - instead
57
Complete Fraction Class (continued) def __mul__(self,other): return Fraction(self._num*other._num, self._den * other._den
def __mul__(self,other): return Fraction(self._num*other._den, self._den * other._num
#include other comparison operators #include float, int, and str conversion operators.
Spot Check• Exercise 6.11• Again, use the discussion board in
Blackboard.
59
Advanced Lessons
#Class-Level Attributes# don't hardwire values such as 0 and 10# volume and 2 and 99 for channelsclass Television:
#class level attributes will be shared by all_minVolume = 0_maxVolume = 10_minChannel = 2_maxChannel = 99
#useTelevision. _minVolume etc instead of hardwired #values that were used before.
60
Advanced Lessons (continued)# Methods that call other methods# By using previously defined setChannel method can # simplify the code.def channelUp(self): if self._powerOn: if self._channel == Television._maxChannel:
goto = Television._minChannel else: goto = self._channel + 1 return self.setChannel(goto)
61
Advanced Lessons (continued)# By separating the wrap-around character-# istics from the actual channel changing the # code is simplified.
# Revised jumpPrevChannel using a # previously defined method. def jumpPrevChannel(self): return self.setChannel(self._prevChan)
Assignment – for next week• Exercise 6.17– Do on your own– You may start a discussion on Blackboard to
discuss aspects of the problem, but not to post specific answers. Do not work together on this one.
– Submit by uploading to the Blackboard site that will be available.
top related