DOC PREVIEW
UW CSE 142 - Python

This preview shows page 1-2-3-4-5 out of 16 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 16 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Unit 8Classes and Objects; InheritanceSpecial thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work.Except where otherwise noted, this work is licensed under:http://creativecommons.org/licenses/by-nc-sa/3.02OOP, Defining a Class• Python was built as a procedural language– OOP exists and works fine, but feels a bit more "tacked on"– Java probably does classes better than Python (gasp)• Declaring a class:class name:statements3Fieldsname = value– Example:class Point:x = 0y = 0# mainp1 = Point()p1.x = 2p1.y = -5– can be declared directly inside class (as shown here)or in constructors (more common)– Python does not really have encapsulation or private fields• relies on caller to "be nice" and not mess with objects' contentspoint.py123class Point:x = 0y = 04Using a Classimport class– client programs must import the classes they usepoint_main.py12345678910from Point import *# mainp1 = Point()p1.x = 7p1.y = -3...# Python objects are dynamic (can add fields any time!)p1.name = "Tyler Durden"5Object Methodsdef name(self, parameter, ..., parameter):statements– selfmustbe the first parameter to any object method• represents the "implicit parameter" (this in Java)–must access the object's fields through the self referenceclass Point:def translate(self, dx, dy):self.x += dxself.y += dy...6"Implicit" Parameter (self)• Java: this, implicitpublic void translate(int dx, int dy) {x += dx; // this.x += dx;y += dy; // this.y += dy;}• Python: self, explicitdef translate(self, dx, dy):self.x += dxself.y += dy– Exercise: Write distance, set_location, and distance_from_origin methods.7Exercise Answerpoint.py1234567891011121314151617from math import *class Point:x = 0y = 0def set_location(self, x, y):self.x = xself.y = ydef distance_from_origin(self):return sqrt(self.x * self.x + self.y * self.y)def distance(self, other):dx = self.x - other.xdy = self.y - other.yreturn sqrt(dx * dx + dy * dy)8Calling Methods• A client can call the methods of an object in two ways:– (the value of self can be an implicit or explicit parameter)1) object.method(parameters)or2) Class.method(object, parameters)• Example:p = Point(3, -4)p.translate(1, 5)Point.translate(p, 1, 5)9Constructorsdef __init__(self, parameter, ..., parameter):statements– a constructor is a special method with the name __init__– Example:class Point:def __init__(self, x, y):self.x = xself.y = y...• How would we make it possible to construct a Point() with no parameters to get (0, 0)?10toString and __str__def __str__(self):return string– equivalent to Java's toString (converts object to a string)– invoked automatically when str or print is calledExercise: Write a __str__ method for Point objects that returns strings like "(3, -14)"def __str__(self):return "(" + str(self.x) + ", " + str(self.y) + ")"11Complete Point Classpoint.py123456789101112131415161718192021from math import *class Point:def __init__(self, x, y):self.x = xself.y = ydef distance_from_origin(self):return sqrt(self.x * self.x + self.y * self.y)def distance(self, other):dx = self.x - other.xdy = self.y - other.yreturn sqrt(dx * dx + dy * dy)def translate(self, dx, dy):self.x += dxself.y += dydef __str__(self):return "(" + str(self.x) + ", " + str(self.y) + ")"12Operator Overloading• operator overloading: You can define functions so that Python's built-in operators can be used with your class.• See also: http://docs.python.org/ref/customization.htmlOperator Class Method-__neg__(self, other)+__pos__(self, other)*__mul__(self, other)/__truediv__(self, other)Unary Operators-__neg__(self)+__pos__(self)Operator Class Method==__eq__(self, other)!=__ne__(self, other)<__lt__(self, other)>__gt__(self, other)<=__le__(self, other)>=__ge__(self, other)13Exercise• Exercise: Write a Fraction class to represent rational numbers like 1/2 and -3/8.• Fractions should always be stored in reduced form; for example, store 4/12 as 1/3 and 6/-9 as -2/3.– Hint: A GCD (greatest common divisor) function may help.• Define add and multiply methods that accept another Fraction as a parameter and modify the existing Fraction by adding/multiplying it by that parameter.• Define +, *, ==, and < operators.14Generating Exceptionsraise ExceptionType("message")– useful when the client uses your object improperly– types: ArithmeticError, AssertionError, IndexError, NameError, SyntaxError, TypeError, ValueError– Example:class BankAccount:...def deposit(self, amount):if amount < 0:raise ValueError("negative amount")...15Inheritanceclass name(superclass):statements– Example:class Point3D(Point): # Point3D extends Pointz = 0...• Python also supports multiple inheritanceclass name(superclass, ..., superclass):statements(if > 1 superclass has the same field/method, conflicts are resolved in left-to-right order)16Calling Superclass Methods• methods: class.method(object, parameters)• constructors: class.__init__(parameters)class Point3D(Point):z = 0def __init__(self, x, y, z):Point.__init__(self, x, y)self.z = zdef translate(self, dx, dy, dz):Point.translate(self, dx, dy)self.z +=


View Full Document

UW CSE 142 - Python

Download Python
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Python and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Python 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?