Classes 3 COMPSCI 105 S2 2015 Principles of Computer Science.

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

Fractions. ADDING FRACTIONS  Build each fraction so that the denominators are the same  ADD the numerators  Place the sum of the two numerators on.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Abstract Data Type Fraction Example
Classes 2 COMPSCI 105 SS 2015 Principles of Computer Science.
Study Guide. a) Has a whole number part & a fraction part b) The answer to a division problem c) For example, 2 1/2 d) Both A and C.
Adding and Subtracting Fractions with Like Denominators.
Fractions.  The Numerator is the number on top  The Denominator is the number on bottom  The Factors of a number are those numbers that will divide.
Object-Oriented Programming in Python Goldwasser and Letscher Chapter 6 Defining Our Own Classes Terry Scott University of Northern Colorado 2007 Prentice.
Adding, subtracting, multiplying, and dividing fractions
Lecture 05 – Classes.  A class provides the definition for the type of an object  Classes can store information in variables  Classes can provide methods.
Simplifying Fractions using GCF. Factor A number that divides evenly into another number. A number that divides evenly into another number.
Classes 2 COMPSCI 105 S Principles of Computer Science.
Simplifying Fractions. October 1, 2012 Standard: 6.NS.1. Interpret & compute quotients of fractions, & solve word problems involving division of fractions.
Exceptions COMPSCI 105 S Principles of Computer Science.
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Chapter 12 More on Classes. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. The three OOP factors Remember,
Chapter 3. Fractions Numerator (top number / part) Denominator (bottom number / whole) Whole Number (1, 2, 3) Fraction (1/2, 2/3, ¾) Mixed Number (1 ½,
Simplifying Fractions
Fractions Revision Lesson EQUIVALENT FRACTIONS Fraction that is worth the same as another fraction but looks different. Eg. 1 = Useful for canceling.
Fractions VI Simplifying Fractions Factor A number that divides evenly into another. Factors of 24 are 1,2, 3, 4, 6, 8, 12 and 24. Factors of 24 are.
Fraction Operations Review Kerbacher. Simplifying Fractions To simplify a fraction: Find the largest number divides evenly into the numerator and denominator.
Adding and Subtracting Fractions
Ordering and Comparing Integers, Decimals, and Fractions
Classes 1 COMPSCI 105 S Principles of Computer Science.
& dding ubtracting ractions.
FRACTIONS & DECIMALS How to add, subtract, multiply, & divide fractions and decimals.
By; Emma Maynard  The numerator is top # in a fraction. Example: 2/4 Numerator.
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.
FRACTIONS LESSON 4. TERMIOLOGY ► NUMERATOR – Top digit of a fraction ► DENOMINATOR – Bottom digit of a fraction ► EQUIVALENT FRACTIONS - are fractions.
Multiplication and Division of Exponents Notes
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Measurement Adding and Subtracting Fractions with Different Denominators.
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 1 Copyright © 2015, 2011, 2007 Pearson Education, Inc. Chapter 1-1 Real Numbers.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Fabulous Fractions Add and Subtract Mixed Numbers.
Warm-up 6-1 Lesson 6-1 Simplifying Rational Expressions.
Warm Up Simplify:. Adding and Subtracting with Unlike Denominators.
Q and A for Sections 6.2, 6.3 Victor Norman CS106.
+ Fractions. + Part of a whole + + Numerator How many pieces The number on the top of a fraction.
Rational Numbers Essential Question: What do we need to do before we can add or subtract fractions? Unit 2 Day 4.
3-5 to 3-6 What You’ll Learn To write equivalent fractions To write equivalent fractions To simplify fractions To simplify fractions To compare and order.
Fractions, Decimals & Percents Key Learning: Fractions, decimals & percents can be used interchangeably. The rules & relationships that govern whole numbers.
Equality, references and mutability COMPSCI 105 SS 2015 Principles of Computer Science.
(Multiplying and Dividing Fractions).   Find common denominator  Make sure you have the lowest common denominator to make your job easier in the end!
COMPSCI 107 Computer Science Fundamentals
COMPSCI 107 Computer Science Fundamentals
Mathematical operators overload
7.1/7.2 – Rational Expressions: Simplifying, Multiplying, and Dividing
Compare Unlike denominators
Introduction to Object-Oriented Programming (OOP) II
Fraction X Adding Unlike Denominators
Warm Up Simplify:.
Warm Up Simplify:.
Adding and Subtracting with Unlike Denominators
Warm Up Simplify:.
Fraction IX Adding Unlike Denominators
MULTIPLYING & DIVIDING FRACTIONS
Which fraction is the same as ?
Terry Scott University of Northern Colorado 2007 Prentice Hall
Fraction X Adding Unlike Denominators
Adding & subtracting Fractions With Common denominator.
Introduction to Object-Oriented Programming (OOP) II
More Basics of Python Common types of data we will work with
Presentation transcript:

Classes 3 COMPSCI 105 S Principles of Computer Science

Exercise  Exercise  Create a Student class:  The Student class should have three attributes: id, last_name, and first_name.  Create a constructor to initialize the values  Implement the __repr__ method and __str__ method Lecture 06COMPSCI 1052 >>> s1 = Student(1, 'Angela', 'Chang') >>> s1 >>> print(s1) >>> s1 = Student(1, 'Angela', 'Chang') >>> s1 >>> print(s1) Student(1, Angela, Chang) 1: Angela Chang Student(1, Angela, Chang) 1: Angela Chang

Reminder – Fraction class  Write a class to represent fractions in Python  create a fraction  add  subtract  multiply  divide  text representation COMPSCI 1053 ½ numerator denominator Lecture 06

Overloading Operators  Python operators work for built-in classes.  But same operator behaves differently with different types.  E.g. the + operator:  perform arithmetic addition on two numbers,  merge two lists  concatenate two strings.  Allow same operator to have different meaning according to the context is called operator overloading Lecture 06COMPSCI 1054 OperatorExpressionInternally Additionf1 + f2f1.__add__(f2) Subtractionf1 - f2f1.__sub__(f2) Equalityf1 == f2f1. __eq__(f2)

The __add__ method  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) COMPSCI 1055 x = Fraction(1, 2) y = Fraction(1, 4) z = x + y print(z) x = Fraction(1, 2) y = Fraction(1, 4) z = x + y print(z) 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) 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) 6/8 Lecture 06

The __sub__ method  The __sub__ method is called when the - operator is used  If we implement __sub__ then we can use - to do subtraction  f1 - f2 gets translated into f1.__sub__(f2) COMPSCI 1056 x = Fraction(1, 2) y = Fraction(1, 4) z = x - y print(z) x = Fraction(1, 2) y = Fraction(1, 4) z = x - y print(z) def __sub__(self, other): new_num = self.__num * other.__den - \ self.__den * other.__num new_den = self.__den * other.__den return Fraction(new_num, new_den) def __sub__(self, other): new_num = self.__num * other.__den - \ self.__den * other.__num new_den = self.__den * other.__den return Fraction(new_num, new_den) 2/8 Lecture 06

The __eq__ method  The __eq__ method checks equality of the objects  Default behaviour is to compare the references  We want to compare the contents COMPSCI 1057 def __eq__(self, other): return self.__num * other.__den == \ other.__num * self.__den def __eq__(self, other): return self.__num * other.__den == \ other.__num * self.__den Lecture 06

Exercise 1  What is the output of the following code? COMPSCI 1058 x = Fraction(2, 3) y = Fraction(1, 3) z = y + y print(x == z) print(x is z) w = x + y print(w == 1) x = Fraction(2, 3) y = Fraction(1, 3) z = y + y print(x == z) print(x is z) w = x + y print(w == 1) Lecture 06 True False True False Print(w == Fraction(1, 1) Print(w == Fraction(9, 9) Print(w == Fraction(1, 1) Print(w == Fraction(9, 9) True AttributeError: 'int' object has no attribute '_Fraction__den'

Improving the __eq__ method  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? COMPSCI 1059 def __eq__(self, other): if not isinstance(other, Fraction): return False return self.__num * other.__den == \ other.__num * self.__den def __eq__(self, other): if not isinstance(other, Fraction): return False return self.__num * other.__den == \ other.__num * self.__den Lecture 06

Improving your code  Fractions:  12/30  2/5  The first fraction can be simplified to 2/5  The Common Factors of 12 and 30 were 1, 2, 3 and 6,  The Greatest Common Factor is 6.  So the largest number we can divide both 12 and 30 evenly by is 6  And so 12/30 can be simplified to 2/5 Lecture 06COMPSCI 10510

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. COMPSCI def __gcd(m, n): while m % n != 0: old_m = m old_n = n m = old_n n = old_m % old_n return n def __gcd(m, n): while m % n != 0: old_m = m old_n = n m = old_n n = old_m % old_n return n Lecture 06

Improve the constructor  We can improve the constructor so that it always represents a fraction using the "lowest terms" form.  What other things might we want to add to a Fraction? COMPSCI class Fraction: def __init__(self, top, bottom): #get the greatest common divisor common = Fraction.__gcd(top, bottom) self.__num = top // common #numerator self.__den = bottom // common #denominator def __gcd(m, n): while m % n != 0: old_m = m old_n = n m = old_n n = old_m % old_n return n class Fraction: def __init__(self, top, bottom): #get the greatest common divisor common = Fraction.__gcd(top, bottom) self.__num = top // common #numerator self.__den = bottom // common #denominator def __gcd(m, n): while m % n != 0: old_m = m old_n = n m = old_n n = old_m % old_n return n Lecture 06

Exercise 2  What is the output of the following code? COMPSCI x = Fraction(2,3) y = Fraction(3,4) z = x + y print(z) w = z - Fraction(7, 12) print(w) print(w + Fraction(1,6) == Fraction(1,1)) x = Fraction(2,3) y = Fraction(3,4) z = x + y print(z) w = z - Fraction(7, 12) print(w) print(w + Fraction(1,6) == Fraction(1,1)) Lecture 06 17/12 5/6 True 17/12 5/6 True

Other standard Python operators  Many standard operators and functions:  Common Arithmetic operators  object.__add__(self, other)  object.__sub__(self, other)  object.__mul__(self, other)  object.__truediv__(self, other )  Common Relational 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) COMPSCI Inplace arithmetic operators  object.__iadd__(self, other)  object.__isub__(self, other)  object.__imul__(self, other)  object.__itruediv__(self, other) Lecture 06

Exercise 3  Implement the following methods of the Fraction class:  Multiplication  i.e. __mul__  Division  i.e. __truediv__ Lecture 06COMPSCI a = Fraction(1, 3) b = Fraction(4, 5) c = a * b d = a / b print (c) print (d) a = Fraction(1, 3) b = Fraction(4, 5) c = a * b d = a / b print (c) print (d) 4/15 5/12 4/15 5/12

Summary  A class is a template, a blueprint and a data type for objects.  A class defines the data fields of objects, and provides an initializer for initializing objects and other methods for manipulating the data.  The initializer always named __init__. The first parameter in each method including the initializer in the class refers to the object that calls the methods, i.e., self.  Data fields in classes should be hidden to prevent data tampering and to make class easy to maintain.  We can overwrite the default methods in a class definition. COMPSCI 10516Lecture 06