1 Programming for Engineers in Python Autumn 2011-12 Lecture 6: More Object Oriented Programming.

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
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.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
More about classes and objects Classes in Visual Basic.NET.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
1 Gentle Introduction to Programming Session 5: Sorting, Searching, Time- Complexity Analysis, Memory Model, Object Oriented Programming.
1 Gentle Introduction to Programming Session 6: Lists, Course Summary.
1 Gentle Introduction to Programming Session 6: Lists, Course Summary.
1 Gentle Introduction to Programming Session 5: Memory Model, Object Oriented Programming.
1 Python Programming: An Introduction to Computer Science Chapter 3 Objects and Graphics.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
College Algebra Fifth Edition
Fundamentals of Python: From First Programs Through Data Structures
Introduction to Object-oriented Programming CSIS 3701: Advanced Object Oriented Programming.
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.
Practical Object-Oriented Design with UML 2e Slide 1/1 ©The McGraw-Hill Companies, 2004 PRACTICAL OBJECT-ORIENTED DESIGN WITH UML 2e Chapter 2: Modelling.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
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.
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Fall 2014.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
COSC 1P03 Data Structures and Abstraction 4.1 Abstract Data Types The advantage of a bad memory is that one enjoys several times the same good things for.
CS 101: “If” and Recursion Abhiram Ranade. This week’ lab assignment: Write a program that takes as input an integer n and a sequence of numbers w1,w2,...,wn.
Input, Output, and Processing
Data Structures Chapter 1- Introduction Mohamed Mustaq.A.
Case Study - Fractions Timothy Budd Oregon State University.
Class Example - Rationals Rational numbers are represented by the ratio of two integers, a numerator and a denominator, e.g., 2/3. This is opposed to irrational.
Chapter 12 More on Classes. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. The three OOP factors Remember,
Classes and Objects The basics. Object-oriented programming Python is an object-oriented programming language, which means that it provides features that.
P Chapter 2 introduces Object Oriented Programming. p OOP is a relatively new approach to programming which supports the creation of new data types and.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
Programming Paradigms Lecturer Hamza Azeem. What is PP ? Revision of Programming concepts learned in CPLB Learning how to perform “Object-Oriented Programming”
Object Oriented Programing (OOP)
Object Oriented Programming
Object-Oriented Programming © 2013 Goodrich, Tamassia, Goldwasser1Object-Oriented Programming.
1 Introduction  Algorithms  Data structures  Abstract data types  Programming with lists and sets © 2008 David A Watt, University of Glasgow Algorithms.
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
CS 106 Introduction to Computer Science I 03 / 22 / 2010 Instructor: Michael Eckmann.
1 Programming for Engineers in Python Autumn Lecture 8: Recursion.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Topics Designing a Program Input, Processing, and Output
Chapter 7: Expressions and Assignment Statements
COMPSCI 107 Computer Science Fundamentals
Topic 7 Introduction to Classes and Objects
CMPT 120 Topic: Functions – Part 4
Chapter 7: Expressions and Assignment Statements
Week 4 Object-Oriented Programming (1): Inheritance
Introduction to Object-Oriented Programming (OOP)
CS360 Windows Programming
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
IFS410: Advanced Analysis and Design
MSIS 670 Object-Oriented Software Engineering
Week 6 Object-Oriented Programming (2): Polymorphism
Week 3 Object-based Programming: Classes and Objects
Introduction to Object-Oriented Programming (OOP)
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chapter 9 Introduction To Classes
Introduction to Object-Oriented Programming (OOP)
Presentation transcript:

1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming

2 Lecture 5 Highlights Functions review Object Oriented Programming

3 is and == is will return True if two variables point to the same object, == if the objects referred to by the variables are equal >>> a = [1, 2, 3] >>> b = a >>> b is a True >>> b == a True >>> b = a[:] >>> b is a False >>> b == a True

4 Object-Oriented Programming (OOP) Represent problem-domain entities using a computer language When building a software in a specific domain, describe the different components of the domain as types and variables Thus we can take another step up in abstraction

5 Class as a Blueprint A class is a blueprint of objects

6 Car Example Members: 4 wheels, steering wheel, horn, color,… Every car instance has its own Methods: drive, turn left, honk, repaint,… Constructors: by color (only), by 4 wheels, engine,…

7 Shapes – 2D Point, Circle __init__ self Attributes Instances and memory Copy (shallow / deep) Methods

8 Code – Define Classes

9 Code – Using Classes

10 Today Continue with 2D Shapes Rational numbers implementation It should feel like native language support Inspired by chapter 6 from the book Programming in Scala

11 A Rectangle (design options) It is not always obvious what the attributes of an object should be How would you represent a rectangle? (for simplicity ignore angle, assume the rectangle is vertical or horizontal) There are several possibilities: One corner / center point + width and height Two opposing corners We shall select the width, height, lower-left corner

12 A Rectangle - Implementation In class Rectangle: Shell:

13 Rectangle in Memory

14 Find Center In class Rectangle: Shell:

15 Grow Rectangle In class Rectangle: Shell:

16 Has Attributes?

17 Print All Attributes

18 Inheritance (briefly) The general idea class Point(object) – what does object stands for? Example: Animals Polymorphism We have seen that already! Histogram example

19 Histogram (polymorphism) Source: Think Python

20 Rational Numbers A rational number is a number that can be expressed as a ratio n/d (n, d integers, d not 0) Examples: 1/2, 2/3, 112/239, 2/1 Not an approximation!

21 Specification print should work smoothly Add, subtract, multiply, divide Immutable It should feel like native language support

22 Constructing a Rational What are the attributes? How a client programmer will create a new Rational object?

23 Constructing a Rational ? Shell:

24 Reimplementing __str__ __str__ method return a string representation of an object A more useful implementation of __str__ would print out the values of the Rational’s numerator and denominator override the default implementation In class Rational: Shell:

25 __repr__ __repr__ method returns the “official” string representation of an object In class Rational: Shell:

26 Checking Preconditions Ensure the data is valid when the object is constructed In class Rational:

27 Checking Preconditions

28 Defining Operators Why not use natural arithmetic operators? Operator precedence will be kept All operations are method calls From the book Programming in Scala

29 Operator Overloading By defining other special methods, you can specify the behavior of operators on user defined types +, -, *, /,,…

30 Adding Rational Numbers

31 Define __add__ Method Immutable In class Rational: Shell:

32 Other Arithmetic Operations In class Rational:

33 Other Arithmetic Operations

34, max INCORRECT!

35, max In class Rational:

36, max How come max works?

Constructors other then the primary? Example: a rational number with a denominator of 1 (e.g., 5/1  5) We would like to do: Rational(5) Default arguments Useful not solely for constructors Remember sorted (reverse, key are default arguments) ? 37 Default Arguments to Constructor

38 Revised Rational In class Rational: Shell:

39 Greatest Common Divisor (gcd) 66/42 = 11/7 To normalize divide the numerator and denominator by their greatest common divisor (gcd) gcd(66,42) = 6  (66/6)/(42/6) = 11/7 No need for Rational clients to be aware of this Encapsulation

40 Off Topic: Calculate gcd (Only if time allows) gcd(a,b) = g a = n * g b = m * g gcd(n,m)=1(otherwise g is not the gcd) a = t * b + r = t * m * g + r  g is a divisor of r gcd(a,b) = gcd(b,a%b) The Euclidean algorithm: repeat iteratively: if (b == 0) return a else repeat using a  b, b  a%b

41 Correctness Example: gcd(40,24)  gcd(24,16)  gcd(16,8)  gcd(8,0)  8 Prove: g = gcd(a,b) = gcd(b,a%b)= g1 g1 is a divisor of a (  g1 ≤ g ) There is no larger divisor of a (  g1 ≥ g ) ≤ : a = t * b + r  a = t * h * g1 + v * g1  g1 is a divisor of a ≥ : assume g > g1  a = t * b + r  g is a divisor of b and r  contradiction

42 gcd Implementation Let’s leave it for next lesson (Recursion) Actually, we can use the implementation in the module fractions.gcd

43 Revised Rational In class Rational: Shell:

44 Mixed Arithmetic's Now we can add and multiply rational numbers! What about mixed arithmetic? r + 2 won’t work  r + Rational(2) is not nice  Add new methods for mixed addition and multiplication Will work thanks to polymorphism

45 Usage The + method invoked is determined in each case by the type of the right operand In our code it is implemented only for the operator + on integers (in “real” life it should have been implemented for every operator and every data type that is supported)

46 Revised __add__ Isinstance takes a value and a class object, and returns True if the vlaue is an instance of the class Handles addition of integers correctly Type based dispatch – dispatches the computation to different executions based on the types of the arguments

47 Implicit Conversions 2 + r  2.+(r)  method call on 2 (int)  int class contains no __add__ method that takes a Rational argument  The problem: Python is asking an integer to add a Rational object, and it doesn’t know how to do that

48 __radd__ - Right Side Add In class Rational: Shell: __radd__ invoked when a Rational object appears on the right side of the + operator

49 Summary Customize classes so that they are natural to use Attributes, methods, constructor Method overriding Encapsulation Define operators as method Method overloading

50 Rational Numbers in Python Actually, there is a Python implementation of Rational numbers It is called fractions

51 Next Week No class (tirgulim as usual) Next topic: Recursion