Introduction to Object-Oriented Programming (OOP)

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

Object-Oriented Programming
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.
Def f(n): if (n == 0): return else: print(“*”) return f(n-1) f(3)
EECS 110: Lec 14: Classes and Objects Aleksandar Kuzmanovic Northwestern University
Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein Classes and Objects Object Oriented Programming.
Lilian Blot TOWARDS MORE ADVANCED CONCEPTS & OBJECT ORIENTED PROGRAMMING Building Data Structure Autumn 2014 TPOP 1.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
ASP.NET Programming with C# and SQL Server First Edition
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Centre for Computer Technology ICT115 Object Oriented Design and Programming Week 2 Intro to Classes Richard Salomon and Umesh Patel Centre for Information.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
A whole new class of programming CS 5 today HW10: Due Sun, Nov 15 Pr0: Ariane 5 Reading Pr1/Lab:the Date class Pr2 Connect4Board Pr3 Connect4Player (extra.
IS 313 Today Schedule Week 0: Classes Objects You're saying that Python's got class ? Dictionaries and Classes Week 1: Week 2: Where.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Def tomorrow(self): """Changes the calling object so that it represents one calendar day after the date it originally represented. """ if self.month in.
By the end of this session you should be able to...
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
Prepared by: Elsy Torres Shajida Berry Siobhan Westby.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
Lists, Tuples, Dictionaries, … + lots of computer work for the programmer's work! T = {'abe' :['homer','herb'], 'jackie':['marge','patty','selma'], 'homer'
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Object Oriented Programing (OOP)
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
IS 313 Today Schedule Week 0: files dictionaries You're saying that Python's got class ? Dictionaries and Classes Week 1: Week 2: Where we've been… Where.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
EECS 110: Lec 14: Classes and Objects
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Introduction to Computing Science and Programming I
EECS 110: Lec 15: Classes and Objects (2)
Guide to Programming with Python
Object Oriented Programming
EECS 110: Lec 17: Review for the Final Exam
COMPSCI 107 Computer Science Fundamentals
Classes and OOP.
CS-104 Final Exam Review Victor Norman.
Copyright (c) 2017 by Dr. E. Horvath
JavaScript Syntax and Semantics
Composition Phil Tayco San Jose City College Slide version 1.2
Conditions and Ifs BIS1523 – Lecture 8.
Introduction to Object-Oriented Programming (OOP) II
CISC101 Reminders Slides have changed from those posted last night…
Operator Overloading; String and Array Objects
Introduction to Object-Oriented Programming (OOP)

EECS 110: Lec 14: Classes and Objects
CS2011 Introduction to Programming I Objects and Classes
Logical Operations In Matlab.
An Introduction to Object Orientated Programming
Objects (again) Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction.
IPC144 Introduction to Programming Using C Week 4 – Lesson 1
Operator Overloading; String and Array Objects
COMPUTER 2430 Object Oriented Programming and Data Structures I
Lecture 18 Python OOP.
Ch. 1 Vocabulary Alice.
Structures Structured Data types Data abstraction structs ---
Introduction to Object-Oriented Programming (OOP)
CMPE212 – Reminders Assignment 2 due next Friday.
Introduction to Object-Oriented Programming (OOP) II
Hardware is… Software is…
Creating and Using Classes
Introduction to Computer Science
Presentation transcript:

Introduction to Object-Oriented Programming (OOP)

So far, we have learned Circuits and basic hardware components in a computer Assembly programming language Python Recursion Lists Functions and parameters Loops The Python elements we learned can be used to accomplish some programming tasks as we have seen.

However, it is more natural to represent things in the real world as objects in a programming language! For example, A car that has an engine, a transmission, … that can move under some instructions … A dog that can walk and bark … A bird that can fly … A book that has chapters and sections, and can be flipped through (read) …

Think, for example, if you are asked to build a program to maintain the information about a collection of books that contains title, author, publisher, date of publishing, and others, how would you do it?

One approach would be to use multiple lists or arrays titles authors publishing_dates To reference the 4th book in the collection, one would use titles[3], authors[3], publishing_dates[3] Another approach would be to define a list (or an array) of book objects, each of which has an author field, a title field, a publishing_date field. When referring to a book, one would use book[3].author, book[3].title, …

Object Oriented Programming An OOP language allows you to create your own types A class is a type An object is a particular instance of that type There can be one instance Or many instances There can be operations (functions, a.k.a., methods) that apply to the object.

Everything in Python is an object! Its capabilities depend on its class. functions class "methods" by the way, you can build your own...

Objects __init__ __str__ An object is a structure - like a list - except (1) Its data elements have names chosen by the programmer. (2) An object contains its own functions that it can call (use)! usually called "fields", "attributes" usually called "methods" instead of functions: __init__ __str__ the constructor the string representation (for printing)

Here’s what a class may look like bigBird = Bird() bigBird.fly() bigBird.eat(20) bigBird.fly()

Compared to what we know already … The use of “Bird” class The use of “String” class sparrow = Bird() print( sparrow) sparrow.fly() sparrow.eat( 20 ) myString = “Hello Halloween” capital = myString.caplitalize() words = myString.split() print( capital ) letterO = words[0].endswith(‘o’) print( letterO )

Date >>> d = Date(3,30,2011) >>> print(d) 03/30/2011 This is a class. It is a user-defined datatype (that you'll build in Lab!) >>> d = Date(3,30,2011) >>> print(d) 03/30/2011 this calls a CONSTRUCTOR … this is an object of type Date the representation of a particular object of type Date >>> d.is_leap_year() False the isLeapYear method returns True or False. How does it know what year to check? >>> d2 = Date(1,1,2012) >>> print(d2) 01/01/2012 >>> d2.is_leap_year() True Another object of type Date - again, from the constructor. How does it know to return True, instead of False in this case ??

class Date: """ a blueprint (class) for objects that represent calendar days """ def __init__( self, mo, dy, yr ): """ the Date constructor """ self.month = mo self.day = dy self.year = yr def __str__( self ): """ used for printing Dates """ s = "{:02d}/{:02d}/{:04d}".format(self.month,self.day,self.year) return s def is_leap_year( self ): """ anyone know the rule? """ The Date class Take time to show this in IDLE, and then create some objects. C/C++ printf style string formatting. See Python string documentation

is the specific OBJECT THAT CALLS A METHOD self is the specific OBJECT THAT CALLS A METHOD >>> d = Date(11,8,2011) >>> print(d) 11/08/2011 These methods need access to the object that calls them >>> d.is_leap_year() False >>> d2 = Date(1,1,2012) >>> print(d2) 01/01/2012 >>> d2.is_leap_year() True These methods need access to the object that calls them

a Leap of faith…. def __init__( self, mo, dy, yr ): (constructor) class Date: def __init__( self, mo, dy, yr ): (constructor) def __str__( self ): (for printing) def is_leap_year( self ): if self.year%400 == 0: return True if self.year%100 == 0: return False return self.year % 4 == 0 John Herschel

Classes – DIY data d = Date( 11, 11, 2011 ) d.tomorrow() print(d) Class: a user-defined datatype Object: data or a variable whose type is a class constructor object d = Date( 11, 11, 2011 ) d.tomorrow() print(d) method d would be named self inside the Date class... uses str Method: a function defined in a class called by an object self: in a class, the name of the object calling a method Constructor: the __init__ function for creating a new object str: the __str__ function returning a string to print data members: the data in self: self.day, self.month, self.year

Date ids >>> d = Date(11,8,2011) >>> print(d) 11/08/2011 >>> d2 = Date(11,9,2011) >>> print(d2) 11/09/2011 this creates a different Date object! >>> d2.yesterday() >>> d == d2 False >>> d == d2 False Take a moment to show how they have different memory locations by using the id() function Point out that yesterday() is a function they will need to work on in Lab

Date ids >>> d = Date(11,8,2011) >>> print(d) 11/08/2011 >>> d2 = Date(11,9,2011) >>> print(d2) 11/09/2011 this initializes a different Date! Need an equals method to check if their VALUES are equal, not their MEMORY ADDRESSES >>> d2.yesterday() >>> d.equals(d2) True >>> d == d2 False

equals class Date: def __init__( self, mo, dy, yr ): def __str__(self): def isLeapYear(self): def equals(self, d2): """ returns True if they represent the same date; False otherwise "”” def equals(self, d2): return self.month == d2.month and self.day == d2.day and self.year == d2.year

References >>> d = Date(11,8,2011) >>> print(d) 11/08/2011 >>> d2 = d >>> print(d2) >>> d.yesterday() 11/07/2011 These refer to the same object! We need a way to make a copy of an object! Simple assignment will not work!

copy class Date: def __init__( self, mo, dy, yr ): def __str__(self): def is_leap_year(self): def equals(self): def copy(self): """ returns a DIFFERENT object w/SAME date value! """ return Date(self.month, self.day, self.year) def copy(self): return Date(self.month,self.day,self.year) Whenever you want to create a brand-new object, use the appropriate CONSTRUCTOR

What's wrong? d = Date(1,1,2012) d2 = Date(11,8,2011) d.is_before( d2 ) True What's wrong? class Date: def is_before(self, d2): """ if self is before d2, this should return True; else False """ if self.year < d2.year: return True if self.month < d2.month: if self.day < d2.day: return False def isBefore(self, d2): """ if self is before d2, this should return True; else False """ if self.year < d2.year: return True if self.month < d2.month and self.year == d2.year: if self.day < d2.day and self.month == d2.month: return False

Better d = Date(1,1,2012) d2 = Date(11,8,2011) d.is_before( d2 ) False class Date: def is_before(self, d2): """ if self is before d2, this should return True; else False """ if self.year < d2.year: return True if self.month < d2.month and self.year == d2.year: if self.day < d2.day and self.month == d2.month: return False def isBefore(self, d2): """ if self is before d2, this should return True; else False """ if self.year < d2.year: return True if self.month < d2.month and self.year == d2.year: if self.day < d2.day and self.month == d2.month: return False

tomorrow() class Date: def tomorrow(self): """ moves the date that calls it ahead 1 day """ monthLen = [0,31,28,31,30,31,30,31,31,30,31,30,31] Write this tomorrow method. first, add 1 to self.day Ignore the leap year the first time through it… give a chance to work on this. if self.isLeapYear() and self.month == 2: monthLen[2] = 29 self.day += 1 if self.day > monthLen[self.month]: self.day = 1 self.month += 1 if self.month == 13: self.month = 1 self.year += 1 then, adjust month and year, if needed

Classes – DIY data d = Date( 11, 11, 2011 ) d.tomorrow() print(d) design-it-yourself! Classes – DIY data Class: a user-defined datatype Object: data or a variable whose type is a class constructor object d = Date( 11, 11, 2011 ) d.tomorrow() print(d) method d would be named self inside the Date class... uses str Method: a function defined in a class called by an object self: in a class, the name of the object calling a method Constructor: the __init__ function for creating a new object str: the __str__ function returning a string to print data members: the data in self: self.day, self.month, self.year

Operator Overload If we define a class of objects, we may be able to or need to reuse some common operators For example, to compare two date objects, can we say something like ‘d1 > d2’ if d1 is AFTER d2? Or for two objects in a rational number class, can we say something like ‘r1 > r2’? Python and any other modern programming languages allow ‘operator overload,’ that is, re-define the meaning of a common operator.

The example of the Rational class From our text book r1 = 1/3, r2 = 2/5, how to do operations such as r1 + r1, or comparisons such as if r1 == r2, or if r1 > r2?