0% found this document useful (0 votes)
8 views

Lecture 17 - Python Classes

Uploaded by

yahya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture 17 - Python Classes

Uploaded by

yahya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

PYTHON CLASSES

(download slides and .py files to follow along)


6.100L Lecture 17
Ana Bell

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:
• 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 str

6.100L Lecture 17
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.100L Lecture 17
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.100L Lecture 17
EXAMPLE:
[1,2,3,4] has type list

 (1) How are lists represented internally?


Does not matter for so much for us as users (private representation)
L = 1 ->2 -> 3
or L = 1 -> 2 -> 3 -> 4 ->
 (2) How to interface with, and 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
5

6.100L Lecture 17
REAL-LIFE EXAMPLES

 Elevator: a box that can change floors


 Represent using length, width, height, max_capacity, current_floor
 Move its location to a different floor, add people, remove people
 Employee: a person who works for a company
 Represent using name, birth_date, salary
 Can change name or salary
 Queue at a store: first customer to arrive is the first one helped
 Represent customers as a list of str names
 Append names to the end and remove names from the beginning
 Stack of pancakes: first pancake made is the last one eaten
 Represent stack as a list of str
 Append pancake to the end and remove from the end
6

6.100L Lecture 17
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.100L Lecture 17
BIG IDEA
You write the class so you
make the design decisions.
You decide what data represents the class.
You decide what operations a user can do with the class.

6.100L Lecture 17
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 the class
• Doing operations on the instances
• for example, L=[1,2] and len(L)

6.100L Lecture 17
A PARALLEL with FUNCTIONS

 Defining a class is like defining a function


 With functions, we tell Python this procedure exists
 With classes, we tell Python about a blueprint for this new data type
 Its data attributes
 Its procedural attributes

 Creating instances of objects is like calling the function


 With functions we make calls with different actual parameters
 With classes, we create new object tinstances in memory of this type
 L1 = [1,2,3]
L2 = [5,6,7]

10

6.100L Lecture 17
COORDINATE TYPE
DESIGN DECISIONS
Can create instances of a  Decide what data elements
Coordinate object constitute an object
• In a 2D plane
• A coordinate is defined by
(3 , 4) an x and y value

 Decide what to do with


coordinates
• Tell us how far away the
coordinate is on the x or y axes
• Measure the distance between
(1 , 1) two coordinates, Pythagoras

11

6.100L Lecture 17
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 (will see in future lects)
12

6.100L Lecture 17
WHAT ARE ATTRIBUTES?

 Data and procedures that “belong” to the class


 Data attributes
• Think of data as other objects/variables 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

13

6.100L Lecture 17
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 class
 Use a special method called __init__ to initialize some
data attributes or perform initialization operations
class Coordinate(object):
def __init__(self, xval, yval):
self.x = xval
self.y = yval

 self allows you to create variables that belong to this object


 Without self, you are just creating regular variables!
14

6.100L Lecture 17
Image © source unknown. All rights
reserved. This content is excluded from
our Creative Commons license. For more

WHAT is self?
information, see https://ocw.mit.edu/
help/faq-fair-use/

ROOM EXAMPLE
 Think of the class definition as a  Now when you create ONE instance
blueprint with placeholders for (name it living_room), self becomes
actual items this actual object
 self has a chair  living_room has a blue chair
 self has a coffee table  living_room has a black table
 self has a sofa  living_room has a white sofa
 Can make many instances using
the same blueprint

15

6.100L Lecture 17
BIG IDEA
When defining a class,
we don’t have an actual
tangible object here.
It’s only a definition.

16

6.100L Lecture 17
Implementing the class Using the class

Recall the __init__ method in the class def:


def __init__(self, xval, yval): ACTUALLY CREATING
self.x = xval
self.y = yval AN INSTANCE OF A CLASS

 Don’t provide argument for self, Python


does this automatically
c = Coordinate(3,4)
origin = Coordinate(0,0)

 Data attributes of an instance are called instance variables


 Data attributes were defined with self.XXX and they are
accessible with dot notation for the lifetime of the object
 All instances have these data attributes, but with different values!
print(c.x)
print(origin.x)
17

6.100L Lecture 17
VISUALIZING INSTANCES

 Suppose we create an instance of


a coordinate
c = Coordinate(3,4) Type: Coordinate
c x: 3
 Think of this as creating a y: 4
structure in memory
 Then evaluating
c.x
looks up the structure to which
c points, then finds the binding
for x in that structure

18

6.100L Lecture 17
VISUALIZING INSTANCES:
in memory
 Make another instance using
a variable
a = 0 Type: Coordinate
c x: 3
orig = Coordinate(a,a) y: 4

orig.x a 0

 All these are just objects in Type: Coordinate


memory! orig x: 0
y: 0
 We just access attributes of
these objects

19

6.100L Lecture 17
VISUALIZING INSTANCES:
draw it

class Coordinate(object):
def __init__(self, xval, yval):
self.x = xval
self.y = yval
(3 , 4)
c
c = Coordinate(3,4)
origin = Coordinate(0,0)
print(c.x)
print(origin.x)

(0 , 0)
origin

20

6.100L Lecture 17
WHAT IS A METHOD?

 Procedural attribute
 Think of it 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

21

6.100L Lecture 17
Implementing the class Using the class

DEFINE A METHOD
FOR THE Coordinate CLASS

class Coordinate(object):
def __init__(self, xval, yval):
self.x = xval
self.y = yval
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)
22

6.100L Lecture 17
HOW TO CALL A METHOD?

 The “.” operator is used to access any attribute


 A data attribute of an object (we saw c.x)
 A method of an object
 Dot notation
<object_variable>.<method>(<parameters>)

 Familiar?
my_list.append(4)
my_list.sort()
23

6.100L Lecture 17
Implementing the class Using the class

Recall the definition of distance method:


def distance(self, other):
HOW TO USE A METHOD
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

Using the class:


c = Coordinate(3,4)
orig = Coordinate(0,0)
print(c.distance(orig))

 Notice that self becomes the object you call the


method on (the thing before the dot!)
24

6.100L Lecture 17
VISUALIZING INVOCATION

 Coordinate class is an object in


memory self.x
self.y
 From the class definition Coordinate __init__: some code
distance: some code
 Create two Coordinate objects
Type: Coordinate
c = Coordinate(3,4) c x: 3
y: 4
orig = Coordinate(0,0)
Type: Coordinate
orig x: 0
y: 0

25

6.100L Lecture 17
VISUALIZING INVOCATION

 Evaluate the method call


c.distance(orig) self.x
self.y
Coordinate __init__: some code
 1) The object is before the dot distance: some code

 2) Looks up the type of c Type: Coordinate


c x: 3
 3) The method to call is after the y: 4

dot. Type: Coordinate


 4) Finds the binding for orig x: 0
y: 0
distance in that object class
 5) Invokes that method with
c as self and
orig as other
26

6.100L Lecture 17
Implementing the class Using the class

HOW TO USE A METHOD

 Conventional way  Equivalent to


c = Coordinate(3,4) c = Coordinate(3,4)
zero = Coordinate(0,0) zero = Coordinate(0,0)
c.distance(zero) Coordinate.distance(c, zero)

27

6.100L Lecture 17
BIG IDEA
The . operator accesses
either data attributes or
methods.
Data attributes are defined with self.something
Methods are functions defined inside the class with self as the first parameter.

28

6.100L Lecture 17
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

29

6.100L Lecture 17
MITOpenCourseWare
https://ocw.mit.edu

6.100L Introduction to Computer Science and Programming Using Python


Fall 2022

For information about citing these materials or our Terms ofUse,visit: https://ocw.mit.edu/terms.

30

You might also like