1 / 20

COMPSCI 107 Computer Science Fundamentals

COMPSCI 107 Computer Science Fundamentals. Lecture 08 – Classes. Recap. Exceptions alter the flow of control When an exception is raised, execution stops When the exception is caught, execution starts again try… except blocks are used to handle problem code

xannon
Download Presentation

COMPSCI 107 Computer Science Fundamentals

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COMPSCI 107Computer Science Fundamentals Lecture 08 – Classes

  2. Recap • Exceptions alter the flow of control • When an exception is raised, execution stops • When the exception is caught, execution starts again • try… except blocks are used to handle problem code • Can ensure that code fails gracefully • Can ensure input is acceptable • raise • Creates a runtime exception • finally • Executes code after the exception handling code COMPSCI 107 - Computer Science Fundamentals

  3. Learning outcomes • At the end of this lecture, students should be able to: • Define a new class • Store state information about instances of the class • Define new methods of the class • Override the default behaviour for standard operations COMPSCI 107 - Computer Science Fundamentals

  4. Classes • Python has a number of classes built-in • lists, dictionaries, sets, int, float, boolean, strings • We can define our own classes • creates a new type of object in Python • Classes consist of: • state variables (sometimes called instance variables) • methods (functions that are linked to a particular instance of the class) class name_of_the_class: definition of the class goes here COMPSCI 107 - Computer Science Fundamentals

  5. Example: Point class • Defining and using a simple class class Point: def __init__(self, loc_x, loc_y): self.x = loc_x self.y = loc_y >>> origin = Point(0, 0) >>> destination = Point(34, 65) >>> destination.x 34 >>> destination.y 65 COMPSCI 107 - Computer Science Fundamentals

  6. Example: Fractions • Write a class to represent fractions in Python • create a fraction • add • subtract • multiply • divide • text representation ½ numerator denominator COMPSCI 107 - Computer Science Fundamentals

  7. Model of objects in memory state state state x 1 7 3 num: num: num: z 4 8 2 den: den: den: y methods methods methods COMPSCI 107 - Computer Science Fundamentals

  8. Constructor • All classes must have a constructor • constructor is a special function that creates the object • always called __init__ • the first argument is always called self • self • a reference to the object that has been created • used to access the state variables and methods of the object class Fraction: def __init__(self, top, bottom): self.num = top #numerator self.den = bottom #denominator COMPSCI 107 - Computer Science Fundamentals

  9. Using the Fraction class • So far, we can create a Fraction • We can access the state variables directly • Although not generally good practice to do so • What else can we do with Fractions? • Nothing yet. We need to write the functions first! >>> x = Fraction(3, 4) >>> x.num 3 >>> x.den 4 COMPSCI 107 - Computer Science Fundamentals

  10. Overriding default behaviour • All classes get a number of methods provided by default • Since default behaviour is not very useful, we should write our own versions of those methods COMPSCI 107 - Computer Science Fundamentals

  11. __repr__ • The __repr__ method produces an string showing an unambiguous way to represent the object (i.e. the "official" representation) • All classes should have a __repr__ function implemented • Ideally, the representation could be used to create the object • For example, a fraction created using Fraction(2, 3) should have a __repr__ method that returned 'Fraction(2, 3)' >>> x = Fraction(2, 3) >>> x <__main__.Fraction object at 0x02762290> def __repr__(self): return 'Fraction(%i, %i)' % (self.num, self.den) >>> x = Fraction(2, 3) >>> x Fraction(2, 3) COMPSCI 107 - Computer Science Fundamentals

  12. __str__ • The __str__ method returns a string representing the object • Default behaviour is to use the __repr__ function (if not implemented, gives us memory) • We should implement a version with a natural representation: • After we have implemented the method, we can use standard Python >>> x = Fraction(3, 4) >>> print(x) <__main__.Fraction object at 0x02714290> def __str__(self): return str(self.num) + '/' + str(self.den) >>> x = Fraction(3, 4) >>> print(x) 3/4 COMPSCI 107 - Computer Science Fundamentals

  13. __add__ • The __add__ method is called when the + operator is used • If we implement __add__ then we can use + to add the objects • f1 + f2 gets translated into f1.__add__(f2) def __add__(self, other): new_num = (self.num * other.den + self.den * other.num) new_den = self.den * other.den return Fraction(new_num, new_den) x = Fraction(1, 2) y = Fraction(1, 4) z = x + y print(z) 6/8 COMPSCI 107 - Computer Science Fundamentals

  14. Greatest Common Divisor • Use Euclid's Algorithm • Given two numbers, n and m, find the number k, such that k is the largest number that evenly divides both n and m. defgcd(m, n): while m % n != 0: old_m = m old_n = n m = old_n n = old_m % old_n return n COMPSCI 107 - Computer Science Fundamentals

  15. Improve the add method • We can improve the add operation to always represent a fraction using the "lowest terms" form. • What other things might we want to add to a Fraction? def__add__(self, other): new_num= self.num* other.den + self.den* other.num new_den= self.den * other.den common = gcd(top, bottom) returnFraction(new_num // common, new_den // common) COMPSCI 107 - Computer Science Fundamentals

  16. __eq__ • The __eq__ method checks equality of the objects • Default behaviouris to compare the references • We want to compare the contents def __eq__(self, other): return self.num* other.den == other.num* self.den COMPSCI 107 - Computer Science Fundamentals

  17. Exercise • What is the output of the following code? x = Fraction(2, 3) y = Fraction(1, 3) z = y + y print(x == z) print(x is z) w = x + y print(w == 1) COMPSCI 107 - Computer Science Fundamentals

  18. Improving __eq__ • Check the type of the other operand • If the type is not a Fraction, then not equal? • What other decisions could we make for equality? def __eq__(self, other): if notisinstance(other, Fraction): return False returnself.num * other.den == other.num * self.den COMPSCI 107 - Computer Science Fundamentals

  19. Other standard Python operators • object.__lt__(self, other) • object.__le__(self, other) • object.__eq__(self, other) • object.__ne__(self, other) • object.__gt__(self, other) • object.__ge__(self, other) • object.__sub__(self, other) • object.__mul__(self, other) • object.__truediv__(self, other) • object.__iadd__(self, other) COMPSCI 107 - Computer Science Fundamentals

  20. Summary Classes are defined using the syntax: Classes contain methods that define the behaviour and operations on objects of that class We override the default behaviours for built-in methods/operations Additional Resources http://interactivepython.org/runestone/static/thinkcspy/Classes/fractions.html class name_of_the_class: definition of the class goes here COMPSCI 107 - Computer Science Fundamentals

More Related