SlideShare a Scribd company logo
1 of 21
Download to read offline
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
 how are lists represented internally? linked list of cells
L =
 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
EXAMPLE:
[1,2,3,4] has type list
6.0001 LECTURE 8 5
1 - 2 - 3 - 4 -
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
 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
CREATING AND USING YOUR
OWN TYPES WITH CLASSES
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
Implementing the class Using the class
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
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
Implementing the class Using the class
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
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))
6.0001 LECTURE 8 14
 equivalent to
c = Coordinate(3,4)
zero = Coordinate(0,0)
print(Coordinate.distance(c, zero))
Implementing the class Using the class
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
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
Implementing the class Using the class
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.

More Related Content

Similar to OOP FUNDAMENTALS IN PYTHON

Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptxGopalNarayan7
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python ClassJim Yeh
 
Python Classes and Objects part13
Python Classes and Objects  part13Python Classes and Objects  part13
Python Classes and Objects part13Vishal Dutt
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaGlenn Guden
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptxakila m
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptxSAICHARANREDDYN
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیMohammad Reza Kamalifard
 
Dev Concepts: Object-Oriented Programming
Dev Concepts: Object-Oriented ProgrammingDev Concepts: Object-Oriented Programming
Dev Concepts: Object-Oriented ProgrammingSvetlin Nakov
 

Similar to OOP FUNDAMENTALS IN PYTHON (20)

Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptx
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Python3
Python3Python3
Python3
 
Python Classes and Objects part13
Python Classes and Objects  part13Python Classes and Objects  part13
Python Classes and Objects part13
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Pythonclass
PythonclassPythonclass
Pythonclass
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
Dev Concepts: Object-Oriented Programming
Dev Concepts: Object-Oriented ProgrammingDev Concepts: Object-Oriented Programming
Dev Concepts: Object-Oriented Programming
 

Recently uploaded

The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Recently uploaded (20)

The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

OOP FUNDAMENTALS IN PYTHON

  • 1. OBJECT ORIENTED PROGRAMMING (download slides and .py filesĂŶĚfollow along!) 6.0001 LECTURE 8 6.0001 LECTURE 8 1
  • 2. 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
  • 3. 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
  • 4. 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
  • 5.  how are lists represented internally? linked list of cells L =  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 EXAMPLE: [1,2,3,4] has type list 6.0001 LECTURE 8 5 1 - 2 - 3 - 4 -
  • 6. 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
  • 7.  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 CREATING AND USING YOUR OWN TYPES WITH CLASSES
  • 8. 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 Implementing the class Using the class
  • 9. 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
  • 10. 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
  • 11. 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 Implementing the class Using the class
  • 12. 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
  • 13. 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
  • 14. 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)) 6.0001 LECTURE 8 14  equivalent to c = Coordinate(3,4) zero = Coordinate(0,0) print(Coordinate.distance(c, zero)) Implementing the class Using the class
  • 15. 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
  • 16. 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
  • 17. 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 Implementing the class Using the class
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. 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.