ICT582 Topic 09
ICT582 Topic 09
§ Testing
§ Debugging
§ Catch exceptions
§ Raise exceptions
§ Assertions
§ Defensive programming
www.codemasterinstitute.com
This Topic
www.codemasterinstitute.com
OBJECTS
6.0001 LECTURE 8 5
OBJECT ORIENTED
PROGRAMMING (OOP)
6.0001 LECTURE 8 6
WHAT ARE OBJECTS?
6.0001 LECTURE 8 7
EXAMPLE: the list [1,2,3,4]
class ClassName:
#define attributes here
§similar to def, indent code to indicate which statements are
part of the class definition
11
WHAT ARE ATTRIBUTES?
13
CREATING AN INSTANCE
OF A CLASS
c = Coordinate(3,4)
origin = Coordinate(0,0)
print(c.x)
print(origin.x)
6.0001 LECTURE 8 15
DEFINE A METHOD FOR THE
Coordinate CLASS
class Coordinate:
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 16
HOW TO USE A METHOD
>>> c = Coordinate(3,4)
>>> print(c)
< main .Coordinate object at 0x7fa918510488>
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)+">"
20
WRAPPING YOUR HEAD AROUND
TYPES AND CLASSES
def __str__(self):
return str(self.numerator)+"/"+str(self.denominator)
www.codemasterinstitute.com
Example: Fractions
def __sub__(self, other):
f = Fraction(0,1)
f.numerator = self.numerator * other.denominator -
other.numerator * self.denominator
f.denominator = self.denominator * other.denominator
return f
f1 = Fraction(1, 3)
f2 = Fraction(3, 5)
f3 = Fraction(2, 6)
print(f1+f2)
print(f1-f2)
print(f1==f2)
print(f1==f3) www.codemasterinstitute.com
THE POWER OF OOP
➢ geekforgeek
➢ MIT OCW