Object-Oriented Programming in Python Goldwasser and Letscher Chapter 6 Defining Our Own Classes Terry Scott University of Northern Colorado 2007 Prentice.

Slides:



Advertisements
Similar presentations
Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 8 Fruitful Functions 05/02/09 Python Mini-Course: Day 2 - Lesson 8 1.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Classes 2 COMPSCI 105 SS 2015 Principles of Computer Science.
True or false A variable of type char can hold the value 301. ( F )
Week 2 Classes, Objects and lists review Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Structured programming
Terry Scott University of Northern Colorado 2007 Prentice Hall
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Object-Oriented Programming in Python Goldwasser and Letscher Chapter 7 Good Software Practices Terry Scott University of Northern Colorado 2007 Prentice.
Lecture 05 – Classes.  A class provides the definition for the type of an object  Classes can store information in variables  Classes can provide methods.
Classes 2 COMPSCI 105 S Principles of Computer Science.
Guide to Programming with Python
Unit 8 Classes and Objects; Inheritance Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except.
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
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.
Classes 3 COMPSCI 105 S Principles of Computer Science.
Python Programming Chapter 14: Classes and Methods Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Object-Oriented Programming in Python Goldwasser and Letscher Chapter 4 Elementary Control Structures Terry Scott University of Northern Colorado 2007.
More Control and Expanded I/O options. Part 1: Defining classes By the end of this session, you should be able to define a class, store it in a file,
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Classes 1 COMPSCI 105 S Principles of Computer Science.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
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.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
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,
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Q and A for Sections 6.2, 6.3 Victor Norman CS106.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Input, Output and Variables GCSE Computer Science – Python.
Adapted from slides by Marty Stepp and Stuart Reges
CMSC201 Computer Science I for Majors Lecture 25 – Classes
COMPSCI 107 Computer Science Fundamentals
Classes and Objects; Inheritance
Classes and Objects – digging deeper
COMPSCI 107 Computer Science Fundamentals
Java Programming: Guided Learning with Early Objects
CS-104 Final Exam Review Victor Norman.
Fundamentals of Programming I More Data Modeling
Functions CIS 40 – Introduction to Programming in Python
User Defined Classes CS F.
Chapter 8 More on Strings and Special Methods
Week 8 Classes and Objects
Chapter (3) - Looping Questions.
Adapted from slides by Marty Stepp and Stuart Reges
Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.
Classes, Objects and lists
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Fundamentals of Programming I More Data Modeling
COMPUTER PROGRAMMING SKILLS
Terry Scott University of Northern Colorado 2007 Prentice Hall
Terry Scott University of Northern Colorado 2007 Prentice Hall
Class code for pythonroom.com cchsp2cs
Presentation transcript:

Object-Oriented Programming in Python Goldwasser and Letscher Chapter 6 Defining Our Own Classes Terry Scott University of Northern Colorado 2007 Prentice Hall

2 Introduction: Chapter 6 Topics Simple point class. Robust point class. Television class. Fraction class. advanced lessons.

3 Predefined versus User Defined Classes Why do classes? It supports reuse of code. Some predefined classes are int, float, list, tuple, boolean, and file. By being able to create our own classes we can configure Python to handle new data types.

4 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,...)

5 Indentation Pattern for a Class

6 Connection Between a Method (setX) for the object corner and setX definition in the class.

7 Two Perspectives Left: perspective from outside the Point class. Right: perspective from inside the Point class.

8 Accessors and Mutators Accessors and mutators let users of the class access data member and change data member values. getX(self) can return the X data member. setX(self, val) will change the X data member to be val.

9 Creating a point class class Point: def __init__(self): self._x = 0 self._y = 0 def getX(self, val): return self._x

10 Point Class (Continued) def setX(self, val): self._x = val def setY(self.val): self._y = val def setY(self, val): self._y = val

11 Using the Point Class #create a new object corner of type Point from SimplePoint import Point corner = Point() corner.setX(8) #8 is value of _x in object corner corner.setY(6) #6 is value of _y in object corner

12 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 = initX self._y = initY #Scales the point by a value factor. def scale(self, factor): self._x *= factor self._y *= factor

13 Improved Point Class (continued) def distance(self, other): dx = self._x - other._x dy = self._y – other._y return sqrt(dx*dx + dy*dy) #using the distance method point1 = Point(5,20) point2 = Point(45,60) apartAmt = point1.distance(point2)

14 Improved Point Class (continued) #normalize point – make its distance to the #origin 1 def normalize(self): mag = self.distance(Point()) #Point() creates new point at origin if mag > 0: #don't scale if point is at origin self.scale(1/mag)

15 Improved Point Class (continued) #allow print to be able to print a point object. def __str__(self): return ' ' #using __str__ method new = Point(3, 5) print new #output

16 Improved Point Class (continued) Can not use to initialize an object. point = #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).

17 Improved Point Class (continued) #overloading operators: + overloading def __add__(other): return Point(self._x +other._x, self._y+other._y #using the __add__ method new = Point(3, 5) old = Point(4, 7) total = new + old print total #output

18 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.

19 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

20 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.

21 Television Class #initializes television object class Television: def __init__(self): self._powerOn = False self.muted = False self._volume = 5 self._channel = 2 self._prevChan = 2

22 Television Class Diagram

23 Television Class (continued) #Clicking flips if on then off and off then on def togglePower(self): self._powerOn = not self._powerOn #Clicking flips between muted and unmuted. def toggleMute(self): if self._powerOn: self._muted = not self._muted

24 Television Class (continued) #volume can range from 1 upto including 10 def volumeUp(self): if self._powerOn: if self._volume < 10: self._volume += 1 self._muted = False return self_volume #volume is #displayed on tv when it is changed.

25 Television Class (continued) #channel increases by one and wraps back to 2 def channelUp(self): if self._powerOn: self._prevChan = self._channel if self._channel == 99: self._channel = 2 else: self._channel += 1 return self._channel

26 Television Class (continued) volumeDown is similar to volumeUp just replace test 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.

27 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

28 Trace of setChannel(7) Tuned to Channel 5 and Was Previously on Channel 2

29 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

30 Flawed Swap of Channels #Left picture is starting situation self._channel = self._prevChan self._prevChan = self._channel #both variables end up at 5

31 One Way to Do This in Python self._channel, self._prevChan=self.prevChan,self._channel

32 Television Class (continued) # previous code #using swap from previous slide incoming = self._channel self._channel = self._prevChan self._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

33 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.

34 Fraction Class Code def __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

35 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

36 Fraction Class Code (continued) # Overloads == operator for fraction objects def __eq__(self, other): return self._num == other._num and self._den == other._den # Overloads float operator for fraction object def __float__(self): return float(self._num) / self._den

37 Fraction Class Code (continued) # overloads int function def __init__(self): return int(float(self)) # overload str function def __str__(self): if self._den == 0: return 'undefined' elif self._den == 1 return str(self._num) else: return str(self._num) + '/' + str(self._den)

38 Complete Fraction Class from gcd import gcd class Fraction: def __init__(self,...) #include constructor code def __add__(self,...) #include + operator code def __sub__(self,...): #similar to __add__ code just - instead

39 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.

40 Advanced Lessons #Class-Level Attributes # don't hardwire values such as 0 and 10 # volume and 2 and 99 for channels class 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.

41 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)

42 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)