OBJECT ORIENTED PROGRAMMING

Similar documents
Programming I. Course 9 Introduction to programming

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

Scientific Programming. Lecture A09 Programming Paradigms

Object Oriented Programming in Python 3

Week 2. Classes and Objects

Lecture 19: Subclasses & Inheritance (Chapter 18)

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Review 2. Classes and Subclasses

What is an algorithm?

PREPARING FOR PRELIM 2

Data Structures (list, dictionary, tuples, sets, strings)

DECOMPOSITION, ABSTRACTION, FUNCTIONS

MITOCW watch?v=flgjisf3l78

CSC148-Section:L0301

Java Object Oriented Design. CSC207 Fall 2014

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Python for Finance. Advanced Features. Andras Niedermayer

PREPARING FOR THE FINAL EXAM

Exceptions. raise type(message) raise Exception(message)

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

CMSC201 Computer Science I for Majors

CSI33 Data Structures

PREPARING FOR THE FINAL EXAM

CS 11 python track: lecture 4

CS558 Programming Languages Winter 2013 Lecture 8

Object Oriented Programming #10

Object Oriented Programming


User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace

Python in 10 (50) minutes

Intro. Classes & Inheritance

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation.

CSC148 Intro. to Computer Science

Week 8 Lecture: Programming

Welcome to CSC148! Introduction to Computer Science

Object Oriented Programming

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

INHERITANCE AND INTERFACES 7

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming

What is an algorithm?

WELCOME! (download slides and.py files and follow along!) LECTURE 1

Lecture 38: Python. CS 51G Spring 2018 Kim Bruce

CSE341: Programming Languages Lecture 23 Multiple Inheritance, Mixins, Interfaces, Abstract Methods. Dan Grossman Autumn 2018

Lecture 17: Classes (Chapter 15)

CSCA08 Winter 2018 Week 2: Variables & Functions. Marzieh Ahmadzadeh, Brian Harrington University of Toronto Scarborough

CSC148-Section:L0301

6.009 Fundamentals of Programming

Class Design (Section 9 of 17)

CSI33 Data Structures

CSE 303: Concepts and Tools for Software Development

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes

CS 1110 Final Exam May 9th, 2013 SOLUTIONS

61A Lecture 2. Friday, August 28, 2015

CSC148 Intro. to Computer Science

Unit E Step-by-Step: Programming with Python

Object Model Comparisons

This quiz is open book and open notes, but do not use a computer.

Algorithms and Programming

Lecture 02, Fall 2018 Friday September 7

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 22 CLASS MICHAEL GROSSBERG

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

CSE 341: Programming Languages. Section AC with Nate Yazdani

CS313D: ADVANCED PROGRAMMING LANGUAGE

OBJECT ORİENTATİON ENCAPSULATİON

Object Orientated Analysis and Design. Benjamin Kenwright

Python Programming Exercises 1

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

CPS 506 Comparative Programming Languages. Programming Language

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005

Chapter 8: Creating Your Own Type Classes

Computational Physics

Introduction to Programming Using Python Lecture 4. Dr. Zhang COSC 1437 Fall, 2018 October 11, 2018

Introduction to Python! Lecture 2

CSE 307: Principles of Programming Languages

61A Lecture 2. Wednesday, September 4, 2013

G Programming Languages - Fall 2012

Before we start looking at how we build abstract data types in Python, let's define some import terms and look at some real-world examples.

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

Compaq Interview Questions And Answers

Today. CSE341: Programming Languages. Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins. Ruby instance variables and methods

Creating a new data type

CSE : Python Programming

Object Oriented Programming

CS1 Lecture 27 Mar. 26, 2018

Object-oriented programming in Python (2)

Professor Hugh C. Lauer CS-1004 Introduction to Programming for Non-Majors

Announcements for This Lecture

Object Oriented Programming

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

Lecture 18. Using Classes Effectively

Iterators & Generators

Computational Mathematics with Python

Transcription:

OBJECT ORIENTED PROGRAMMING (download slides and.py files follow along!) 6.0001 LECTURE 8 6.0001 LECTURE 8 1

OBJECTS Python supports many different kinds of data 1234 3.14159 "Hello" [1, 5, 7, 11, 13] {"CA": "California", "MA": "Massachusetts"} each is an object, and every object has: a type an internal data representation (primitive or composite) a set of procedures for interaction with the object an object is an instance of a type 1234 is an instance of an int "hello" is an instance of a string 6.0001 LECTURE 8 2

OBJECT ORIENTED PROGRAMMING (OOP) EVERYTHING IN PYTHON IS AN OBJECT (and has a type) can create new objects of some type can manipulate objects can destroy objects explicitly using del or just forget about them python system will reclaim destroyed or inaccessible objects called garbage collection 6.0001 LECTURE 8 3

WHAT ARE OBJECTS? objects are a data abstraction that captures (1) an internal representation through data attributes (2) an interface for interacting with object through methods (aka procedures/functions) defines behaviors but hides implementation 6.0001 LECTURE 8 4

EXAMPLE: [1,2,3,4] has type list how are lists represented internally? linked list of cells L = 1 -> 2 -> 3 -> 4 -> how to manipulate lists? L[i], L[i:j], + len(), min(), max(), del(l[i]) L.append(),L.extend(),L.count(),L.index(), L.insert(),L.pop(),L.remove(),L.reverse(), L.sort() internal representation should be private correct behavior may be compromised if you manipulate internal representation directly 6.0001 LECTURE 8 5

ADVANTAGES OF OOP bundle data into packages together with procedures that work on them through well-defined interfaces divide-and-conquer development implement and test behavior of each class separately increased modularity reduces complexity classes make it easy to reuse code many Python modules define new classes each class has a separate environment (no collision on function names) inheritance allows subclasses to redefine or extend a selected subset of a superclass behavior 6.0001 LECTURE 8 6

Implementing the class Using the class CREATING AND USING YOUR OWN TYPES WITH CLASSES make a distinction between creating a class and using an instance of the class creating the class involves defining the class name defining class attributes for example, someone wrote code to implement a list class using the class involves creating new instances of objects doing operations on the instances for example, L=[1,2] and len(l) 6.0001 LECTURE 8 7

Implementing the class Using the class DEFINE YOUR OWN TYPES use the class keyword to define a new type class Coordinate(object): #define attributes here similar to def, indent code to indicate which statements are part of the class definition the word object means that Coordinate is a Python object and inherits all its attributes (inheritance next lecture) Coordinate is a subclass of object object is a superclass of Coordinate 6.0001 LECTURE 8 8

WHAT ARE ATTRIBUTES? data and procedures that belong to the class data attributes think of data as other objects that make up the class for example, a coordinate is made up of two numbers methods (procedural attributes) think of methods as functions that only work with this class how to interact with the object for example you can define a distance between two coordinate objects but there is no meaning to a distance between two list objects 6.0001 LECTURE 8 9

Implementing the class Using the class DEFINING HOW TO CREATE AN INSTANCE OF A CLASS first have to define how to create an instance of object use a special method called init to initialize some data attributes class Coordinate(object): def init (self, x, y): self.x = x self.y = y 6.0001 LECTURE 8 10

Implementing the class Using the class ACTUALLY CREATING AN INSTANCE OF A CLASS c = Coordinate(3,4) origin = Coordinate(0,0) print(c.x) print(origin.x) data attributes of an instance are called instance variables don t provide argument for self, Python does this automatically 6.0001 LECTURE 8 11

WHAT IS A METHOD? procedural attribute, like a function that works only with this class Python always passes the object as the first argument convention is to use self as the name of the first argument of all methods the. operator is used to access any attribute a data attribute of an object a method of an object 6.0001 LECTURE 8 12

Implementing the class Using the class DEFINE A METHOD FOR THE Coordinate CLASS class Coordinate(object): def init (self, x, y): self.x = x self.y = y def distance(self, other): x_diff_sq = (self.x-other.x)**2 y_diff_sq = (self.y-other.y)**2 return (x_diff_sq + y_diff_sq)**0.5 other than self and dot notation, methods behave just like functions (take params, do operations, return) 6.0001 LECTURE 8 13

Implementing the class Using the class HOW TO USE A METHOD def distance(self, other): # code here Using the class: conventional way c = Coordinate(3,4) zero = Coordinate(0,0) print(c.distance(zero)) equivalent to c = Coordinate(3,4) zero = Coordinate(0,0) print(coordinate.distance(c, zero)) 6.0001 LECTURE 8 14

PRINT REPRESENTATION OF AN OBJECT >>> c = Coordinate(3,4) >>> print(c) < main.coordinate object at 0x7fa918510488> uninformative print representation by default define a str method for a class Python calls the str method when used with print on your class object you choose what it does! Say that when we print a Coordinate object, want to show >>> print(c) <3,4> 6.0001 LECTURE 8 15

Implementing the class Using the class DEFINING YOUR OWN PRINT METHOD class Coordinate(object): def init (self, x, y): self.x = x self.y = y def distance(self, other): x_diff_sq = (self.x-other.x)**2 y_diff_sq = (self.y-other.y)**2 return (x_diff_sq + y_diff_sq)**0.5 def str (self): return "<"+str(self.x)+","+str(self.y)+">" 6.0001 LECTURE 8 16

Implementing the class Using the class WRAPPING YOUR HEAD AROUND TYPES AND CLASSES can ask for the type of an object instance >>> c = Coordinate(3,4) >>> print(c) <3,4> >>> print(type(c)) <class main.coordinate> this makes sense since >>> print(coordinate) <class main.coordinate> >>> print(type(coordinate)) <type 'type'> use isinstance() to check if an object is a Coordinate >>> print(isinstance(c, Coordinate)) True 6.0001 LECTURE 8 17

SPECIAL OPERATORS +, -, ==, <, >, len(), print, and many others https://docs.python.org/3/reference/datamodel.html#basic-customization like print, can override these to work with your class define them with double underscores before/after add (self, other) self + other sub (self, other) self - other eq (self, other) self == other lt (self, other) self < other len (self) len(self) str (self) print self... and others 6.0001 LECTURE 8 18

EXAMPLE: FRACTIONS create a new type to represent a number as a fraction internal representation is two integers numerator denominator interface a.k.a. methods a.k.a how to interact with Fraction objects add, subtract print representation, convert to a float invert the fraction the code for this is in the handout, check it out! 6.0001 LECTURE 8 19

THE POWER OF OOP bundle together objects that share common attributes and procedures that operate on those attributes use abstraction to make a distinction between how to implement an object vs how to use the object build layers of object abstractions that inherit behaviors from other classes of objects create our own classes of objects on top of Python s basic classes 6.0001 LECTURE 8 20

MIT OpenCourseWare https://ocw.mit.edu 6.0001 Introduction to Computer Science and Programming in Python Fall 2016 For information about citing these materials or our Terms of Use, visit: https://ocw.mit.edu/terms.