SlideShare a Scribd company logo
1 of 26
Download to read offline
PYTHON CLASSES
and INHERITANCE
(download slides and .py files ĂŶĚfollow along!)
6.0001 LECTURE 9
6.0001 LECTURE 9 1
LAST TIME
 abstract data types through classes
 Coordinate example
 Fraction example
 more on classes
• getters and setters
• information hiding
• class variables
 inheritance
6.0001 LECTURE 9 2
TODAY
IMPLEMENTING USING
THE CLASS vs THE CLASS
implementing a new
object type with a class
• define the class
• define data attributes
(WHAT IS the object)
• define methods
(HOW TO use the object)
6.0001 LECTURE 9 3
using the new object type in
code
• create instances of the
object type
• do operations with them
 write code from two different perspectives
CLASS DEFINITION INSTANCE
OF AN OBJECT TYPE vs OF A CLASS
 class name is the type
class Coordinate(object)
 class is defined generically
• use self to refer to some
instance while defining the
class
(self.x – self.y)**2
• self is a parameter to
methods in class definition
 class defines data and
methods common across all
instances
6.0001 LECTURE 9 4
 instance is one specific object
coord = Coordinate(1,2)
 data attribute values vary
between instances
c1 = Coordinate(1,2)
c2 = Coordinate(3,4)
• c1 and c2 have different data
attribute values c1.x and c2.x
because they are different
objects
 instance has the structure of
the class
WHY USE OOP AND
CLASSES OF OBJECTS?
• mimic real life
• group different objects part of the same type
6.0001 LECTURE 9 5
Image Credits, clockwise from top: Image Courtesy Harald Wehner, in the public Domain. Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CC-
BY-NC-SA. Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY
WHY USE OOP AND
CLASSES OF OBJECTS?
• mimic real life
• group different objects part of the same type
6.0001 LECTURE 9 6
6.0001 LECTURE 9 6
Image Credits, clockwise from top: Image Courtesy Harald Wehner, in the public Domain. Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CC-
BY-NC-SA. Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY
GROUPS OF OBJECTS HAVE
ATTRIBUTES (RECAP)
 data attributes
• how can you represent your object with data?
• what it is
• for a coordinate: x and y values
• for an animal: age, name
 procedural attributes (behavior/operations/methods)
• how can someone interact with the object?
• what it does
• for a coordinate: find distance between two
• for an animal: make a sound
6.0001 LECTURE 9 7
HOW TO DEFINE A CLASS
(RECAP)
class Animal(object):
def __init__(self, age):
self.age = age
self.name = None
myanimal = Animal(3)
6.0001 LECTURE 9 8
GETTER AND SETTER METHODS
class Animal(object):
def __init__(self, age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self, newage):
self.age = newage
def set_name(self, newname=):
self.name = newname
def __str__(self):
return animal:+str(self.name)+:+str(self.age)
 getters and setters should be used outside of class to
access data attributes
6.0001 LECTURE 9 9
AN INSTANCE and
DOT NOTATION (RECAP)
 instantiation creates an instance of an object
a = Animal(3)
 dot notation used to access attributes (data and
methods) though it is better to use getters and setters
to access data attributes
a.age
a.get_age()
6.0001 LECTURE 9 10
INFORMATION HIDING
 author of class definition may change data attribute
variable names
class Animal(object):
def __init__(self, age):
self.years = age
def get_age(self):
return self.years
 if you are accessing data attributes outside the class and
class definition changes, may get errors
 outside of class, use getters and setters instead
use a.get_age() NOT a.age
• good style
• easy to maintain code
• prevents bugs
6.0001 LECTURE 9 11
PYTHON NOT GREAT AT
INFORMATION HIDING
 allows you to access data from outside class definition
print(a.age)
 allows you to write to data from outside class definition
a.age = 'infinite'
 allows you to create data attributes for an instance from
outside class definition
a.size = tiny
 it’s not good style to do any of these!
6.0001 LECTURE 9 12
DEFAULT ARGUMENTS
 default arguments for formal parameters are used if no
actual argument is given
def set_name(self, newname=):
self.name = newname
 default argument used here
a = Animal(3)
a.set_name()
print(a.get_name())
 argument passed in is used here
a = Animal(3)
a.set_name(fluffy)
print(a.get_name())
6.0001 LECTURE 9 13
HIERARCHIES
6.0001 LECTURE 9 14
Image Credits, clockwise from top: Image Courtesy Deeeep, CC-BY-NC. Image Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CC-BY-NC-SA.
Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY. Courtesy
Harald Wehner, in the public Domain.
Animal
Cat Rabbit
HIERARCHIES
 parent class
(superclass)
 child class
(subclass)
• inherits all data Person
and behaviors of
parent class
• add more info
• add more behavior
• override behavior
Student
6.0001 LECTURE 9 15
INHERITANCE:
PARENT CLASS
class Animal(object):
def __init__(self, age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self, newage):
self.age = newage
def set_name(self, newname=):
self.name = newname
def __str__(self):
return animal:+str(self.name)+:+str(self.age)
6.0001 LECTURE 9 16
INHERITANCE:
SUBCLASS
class Cat(Animal):
def speak(self):
print(meow)
def __str__(self):
return cat:+str(self.name)+:+str(self.age)
 add new functionality with speak()
• instance of type Cat can be called with new methods
• instance of type Animal throws error if called with Cat’s
new method
 __init__ is not missing, uses the Animal version
6.0001 LECTURE 9 17
WHICH METHOD TO USE?
• subclass can have methods with same name as
superclass
• for an instance of a class, look for a method name in
current class definition
• if not found, look for method name up the hierarchy
(in parent, then grandparent, and so on)
• use first method up the hierarchy that you found with
that method name
6.0001 LECTURE 9 18
class Person(Animal):
def __init__(self, name, age):
Animal.__init__(self, age)
self.set_name(name)
self.friends = []
def get_friends(self):
return self.friends
def add_friend(self, fname):
if fname not in self.friends:
self.friends.append(fname)
def speak(self):
print(hello)
def age_diff(self, other):
diff = self.age - other.age
print(abs(diff), year difference)
def __str__(self):
return person:+str(self.name)+:+str(self.age)
6.0001 LECTURE 9 19
import random
class Student(Person):
def __init__(self, name, age, major=None):
Person.__init__(self, name, age)
self.major = major
def change_major(self, major):
self.major = major
def speak(self):
r = random.random()
if r  0.25:
print(i have homework)
elif 0.25 = r  0.5:
print(i need sleep)
elif 0.5 = r  0.75:
print(i should eat)
else:
print(i am watching tv)
def __str__(self):
return student:+str(self.name)+:+str(self.age)+:+str(self.major)
6.0001 LECTURE 9 20
CLASS VARIABLES AND THE
Rabbit SUBCLASS
 class variables and their values are shared between all
instances of a class
class Rabbit(Animal):
tag = 1
def __init__(self, age, parent1=None, parent2=None):
Animal.__init__(self, age)
self.parent1 = parent1
self.parent2 = parent2
self.rid = Rabbit.tag
Rabbit.tag += 1
 tag used to give unique id to each new rabbit instance
6.0001 LECTURE 9 21
Rabbit GETTER METHODS
class Rabbit(Animal):
tag = 1
def __init__(self, age, parent1=None, parent2=None):
Animal.__init__(self, age)
self.parent1 = parent1
self.parent2 = parent2
self.rid = Rabbit.tag
Rabbit.tag += 1
def get_rid(self):
return str(self.rid).zfill(3)
def get_parent1(self):
return self.parent1
def get_parent2(self):
return self.parent2
6.0001 LECTURE 9 22
WORKING WITH YOUR OWN
TYPES
def __add__(self, other):
# returning object of same type as this class
return Rabbit(0, self, other)
 define + operator between two Rabbit instances
• define what something like this does: r4 = r1 + r2
where r1 and r2 are Rabbit instances
• r4 is a new Rabbit instance with age 0
• r4 has self as one parent and other as the other parent
• in __init__, parent1 and parent2 are of type Rabbit
6.0001 LECTURE 9 23
recall Rabbit’s __init__(self, age, parent1=None, parent2=None)
SPECIAL METHOD TO
COMPARE TWO Rabbits
 decide that two rabbits are equal if they have the same two
parents
def __eq__(self, other):
parents_same = self.parent1.rid == other.parent1.rid 
and self.parent2.rid == other.parent2.rid
parents_opposite = self.parent2.rid == other.parent1.rid 
and self.parent1.rid == other.parent2.rid
return parents_same or parents_opposite
 compare ids of parents since ids are unique (due to class var)
 note you can’t compare objects directly
• for ex. with self.parent1 == other.parent1
• this calls the __eq__ method over and over until call it on None and
gives an AttributeError when it tries to do None.parent1
6.0001 LECTURE 9 24
OBJECT ORIENTED
PROGRAMMING
 create your own collections of data
 organize information
 division of work
 access information in a consistent manner
 add layers of complexity
 like functions, classes are a mechanism for
decomposition and abstraction in programming
6.0001 LECTURE 9 25
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 classes and objects.pdf

The Ring programming language version 1.4.1 book - Part 20 of 31
The Ring programming language version 1.4.1 book - Part 20 of 31The Ring programming language version 1.4.1 book - Part 20 of 31
The Ring programming language version 1.4.1 book - Part 20 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 77 of 196
The Ring programming language version 1.7 book - Part 77 of 196The Ring programming language version 1.7 book - Part 77 of 196
The Ring programming language version 1.7 book - Part 77 of 196Mahmoud Samir Fayed
 
oops -concepts
oops -conceptsoops -concepts
oops -conceptssinhacp
 
The Ring programming language version 1.3 book - Part 56 of 88
The Ring programming language version 1.3 book - Part 56 of 88The Ring programming language version 1.3 book - Part 56 of 88
The Ring programming language version 1.3 book - Part 56 of 88Mahmoud Samir Fayed
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
38-object-concepts.ppt
38-object-concepts.ppt38-object-concepts.ppt
38-object-concepts.pptRavi Kumar
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)Shambhavi Vats
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-conceptsraahulwasule
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیMohammad Reza Kamalifard
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptxSAICHARANREDDYN
 
The Ring programming language version 1.6 book - Part 75 of 189
The Ring programming language version 1.6 book - Part 75 of 189The Ring programming language version 1.6 book - Part 75 of 189
The Ring programming language version 1.6 book - Part 75 of 189Mahmoud Samir Fayed
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
Ground Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - ClassesGround Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - ClassesChariza Pladin
 

Similar to classes and objects.pdf (20)

The Ring programming language version 1.4.1 book - Part 20 of 31
The Ring programming language version 1.4.1 book - Part 20 of 31The Ring programming language version 1.4.1 book - Part 20 of 31
The Ring programming language version 1.4.1 book - Part 20 of 31
 
S12.s01 - Material TP.pdf
S12.s01 - Material TP.pdfS12.s01 - Material TP.pdf
S12.s01 - Material TP.pdf
 
The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84The Ring programming language version 1.2 book - Part 53 of 84
The Ring programming language version 1.2 book - Part 53 of 84
 
The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180The Ring programming language version 1.5.1 book - Part 69 of 180
The Ring programming language version 1.5.1 book - Part 69 of 180
 
The Ring programming language version 1.7 book - Part 77 of 196
The Ring programming language version 1.7 book - Part 77 of 196The Ring programming language version 1.7 book - Part 77 of 196
The Ring programming language version 1.7 book - Part 77 of 196
 
oops -concepts
oops -conceptsoops -concepts
oops -concepts
 
The Ring programming language version 1.3 book - Part 56 of 88
The Ring programming language version 1.3 book - Part 56 of 88The Ring programming language version 1.3 book - Part 56 of 88
The Ring programming language version 1.3 book - Part 56 of 88
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
38-object-concepts.ppt
38-object-concepts.ppt38-object-concepts.ppt
38-object-concepts.ppt
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)
 
38 object-concepts
38 object-concepts38 object-concepts
38 object-concepts
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
Basic object oriented concepts (1)
Basic object oriented concepts (1)Basic object oriented concepts (1)
Basic object oriented concepts (1)
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
The Ring programming language version 1.6 book - Part 75 of 189
The Ring programming language version 1.6 book - Part 75 of 189The Ring programming language version 1.6 book - Part 75 of 189
The Ring programming language version 1.6 book - Part 75 of 189
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Ground Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - ClassesGround Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - Classes
 
OOPS
OOPSOOPS
OOPS
 

Recently uploaded

CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 

Recently uploaded (20)

CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 

classes and objects.pdf

  • 1. PYTHON CLASSES and INHERITANCE (download slides and .py files ĂŶĚfollow along!) 6.0001 LECTURE 9 6.0001 LECTURE 9 1
  • 2. LAST TIME  abstract data types through classes  Coordinate example  Fraction example  more on classes • getters and setters • information hiding • class variables  inheritance 6.0001 LECTURE 9 2 TODAY
  • 3. IMPLEMENTING USING THE CLASS vs THE CLASS implementing a new object type with a class • define the class • define data attributes (WHAT IS the object) • define methods (HOW TO use the object) 6.0001 LECTURE 9 3 using the new object type in code • create instances of the object type • do operations with them  write code from two different perspectives
  • 4. CLASS DEFINITION INSTANCE OF AN OBJECT TYPE vs OF A CLASS  class name is the type class Coordinate(object)  class is defined generically • use self to refer to some instance while defining the class (self.x – self.y)**2 • self is a parameter to methods in class definition  class defines data and methods common across all instances 6.0001 LECTURE 9 4  instance is one specific object coord = Coordinate(1,2)  data attribute values vary between instances c1 = Coordinate(1,2) c2 = Coordinate(3,4) • c1 and c2 have different data attribute values c1.x and c2.x because they are different objects  instance has the structure of the class
  • 5. WHY USE OOP AND CLASSES OF OBJECTS? • mimic real life • group different objects part of the same type 6.0001 LECTURE 9 5 Image Credits, clockwise from top: Image Courtesy Harald Wehner, in the public Domain. Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CC- BY-NC-SA. Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY
  • 6. WHY USE OOP AND CLASSES OF OBJECTS? • mimic real life • group different objects part of the same type 6.0001 LECTURE 9 6 6.0001 LECTURE 9 6 Image Credits, clockwise from top: Image Courtesy Harald Wehner, in the public Domain. Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CC- BY-NC-SA. Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY
  • 7. GROUPS OF OBJECTS HAVE ATTRIBUTES (RECAP)  data attributes • how can you represent your object with data? • what it is • for a coordinate: x and y values • for an animal: age, name  procedural attributes (behavior/operations/methods) • how can someone interact with the object? • what it does • for a coordinate: find distance between two • for an animal: make a sound 6.0001 LECTURE 9 7
  • 8. HOW TO DEFINE A CLASS (RECAP) class Animal(object): def __init__(self, age): self.age = age self.name = None myanimal = Animal(3) 6.0001 LECTURE 9 8
  • 9. GETTER AND SETTER METHODS class Animal(object): def __init__(self, age): self.age = age self.name = None def get_age(self): return self.age def get_name(self): return self.name def set_age(self, newage): self.age = newage def set_name(self, newname=): self.name = newname def __str__(self): return animal:+str(self.name)+:+str(self.age)  getters and setters should be used outside of class to access data attributes 6.0001 LECTURE 9 9
  • 10. AN INSTANCE and DOT NOTATION (RECAP)  instantiation creates an instance of an object a = Animal(3)  dot notation used to access attributes (data and methods) though it is better to use getters and setters to access data attributes a.age a.get_age() 6.0001 LECTURE 9 10
  • 11. INFORMATION HIDING  author of class definition may change data attribute variable names class Animal(object): def __init__(self, age): self.years = age def get_age(self): return self.years  if you are accessing data attributes outside the class and class definition changes, may get errors  outside of class, use getters and setters instead use a.get_age() NOT a.age • good style • easy to maintain code • prevents bugs 6.0001 LECTURE 9 11
  • 12. PYTHON NOT GREAT AT INFORMATION HIDING  allows you to access data from outside class definition print(a.age)  allows you to write to data from outside class definition a.age = 'infinite'  allows you to create data attributes for an instance from outside class definition a.size = tiny  it’s not good style to do any of these! 6.0001 LECTURE 9 12
  • 13. DEFAULT ARGUMENTS  default arguments for formal parameters are used if no actual argument is given def set_name(self, newname=): self.name = newname  default argument used here a = Animal(3) a.set_name() print(a.get_name())  argument passed in is used here a = Animal(3) a.set_name(fluffy) print(a.get_name()) 6.0001 LECTURE 9 13
  • 14. HIERARCHIES 6.0001 LECTURE 9 14 Image Credits, clockwise from top: Image Courtesy Deeeep, CC-BY-NC. Image Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CC-BY-NC-SA. Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY. Courtesy Harald Wehner, in the public Domain.
  • 15. Animal Cat Rabbit HIERARCHIES  parent class (superclass)  child class (subclass) • inherits all data Person and behaviors of parent class • add more info • add more behavior • override behavior Student 6.0001 LECTURE 9 15
  • 16. INHERITANCE: PARENT CLASS class Animal(object): def __init__(self, age): self.age = age self.name = None def get_age(self): return self.age def get_name(self): return self.name def set_age(self, newage): self.age = newage def set_name(self, newname=): self.name = newname def __str__(self): return animal:+str(self.name)+:+str(self.age) 6.0001 LECTURE 9 16
  • 17. INHERITANCE: SUBCLASS class Cat(Animal): def speak(self): print(meow) def __str__(self): return cat:+str(self.name)+:+str(self.age)  add new functionality with speak() • instance of type Cat can be called with new methods • instance of type Animal throws error if called with Cat’s new method  __init__ is not missing, uses the Animal version 6.0001 LECTURE 9 17
  • 18. WHICH METHOD TO USE? • subclass can have methods with same name as superclass • for an instance of a class, look for a method name in current class definition • if not found, look for method name up the hierarchy (in parent, then grandparent, and so on) • use first method up the hierarchy that you found with that method name 6.0001 LECTURE 9 18
  • 19. class Person(Animal): def __init__(self, name, age): Animal.__init__(self, age) self.set_name(name) self.friends = [] def get_friends(self): return self.friends def add_friend(self, fname): if fname not in self.friends: self.friends.append(fname) def speak(self): print(hello) def age_diff(self, other): diff = self.age - other.age print(abs(diff), year difference) def __str__(self): return person:+str(self.name)+:+str(self.age) 6.0001 LECTURE 9 19
  • 20. import random class Student(Person): def __init__(self, name, age, major=None): Person.__init__(self, name, age) self.major = major def change_major(self, major): self.major = major def speak(self): r = random.random() if r 0.25: print(i have homework) elif 0.25 = r 0.5: print(i need sleep) elif 0.5 = r 0.75: print(i should eat) else: print(i am watching tv) def __str__(self): return student:+str(self.name)+:+str(self.age)+:+str(self.major) 6.0001 LECTURE 9 20
  • 21. CLASS VARIABLES AND THE Rabbit SUBCLASS  class variables and their values are shared between all instances of a class class Rabbit(Animal): tag = 1 def __init__(self, age, parent1=None, parent2=None): Animal.__init__(self, age) self.parent1 = parent1 self.parent2 = parent2 self.rid = Rabbit.tag Rabbit.tag += 1  tag used to give unique id to each new rabbit instance 6.0001 LECTURE 9 21
  • 22. Rabbit GETTER METHODS class Rabbit(Animal): tag = 1 def __init__(self, age, parent1=None, parent2=None): Animal.__init__(self, age) self.parent1 = parent1 self.parent2 = parent2 self.rid = Rabbit.tag Rabbit.tag += 1 def get_rid(self): return str(self.rid).zfill(3) def get_parent1(self): return self.parent1 def get_parent2(self): return self.parent2 6.0001 LECTURE 9 22
  • 23. WORKING WITH YOUR OWN TYPES def __add__(self, other): # returning object of same type as this class return Rabbit(0, self, other)  define + operator between two Rabbit instances • define what something like this does: r4 = r1 + r2 where r1 and r2 are Rabbit instances • r4 is a new Rabbit instance with age 0 • r4 has self as one parent and other as the other parent • in __init__, parent1 and parent2 are of type Rabbit 6.0001 LECTURE 9 23 recall Rabbit’s __init__(self, age, parent1=None, parent2=None)
  • 24. SPECIAL METHOD TO COMPARE TWO Rabbits  decide that two rabbits are equal if they have the same two parents def __eq__(self, other): parents_same = self.parent1.rid == other.parent1.rid and self.parent2.rid == other.parent2.rid parents_opposite = self.parent2.rid == other.parent1.rid and self.parent1.rid == other.parent2.rid return parents_same or parents_opposite  compare ids of parents since ids are unique (due to class var)  note you can’t compare objects directly • for ex. with self.parent1 == other.parent1 • this calls the __eq__ method over and over until call it on None and gives an AttributeError when it tries to do None.parent1 6.0001 LECTURE 9 24
  • 25. OBJECT ORIENTED PROGRAMMING  create your own collections of data  organize information  division of work  access information in a consistent manner  add layers of complexity  like functions, classes are a mechanism for decomposition and abstraction in programming 6.0001 LECTURE 9 25
  • 26. 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.