[go: up one dir, main page]

0% found this document useful (0 votes)
8 views28 pages

ICT582 Topic 09

Uploaded by

bhattibaba118
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views28 pages

ICT582 Topic 09

Uploaded by

bhattibaba118
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Topic 9

Object Oriented Programming


Last Topic

§ Testing
§ Debugging
§ Catch exceptions
§ Raise exceptions
§ Assertions
§ Defensive programming

www.codemasterinstitute.com
This Topic

§ Class and objects


§ Class definition
§ Create objects from a class
§ Operator methods
§ Solving problems with classes and objects

www.codemasterinstitute.com
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, eg,
• 1234 is an instance of an int
• "hello" is an instance of a string
6.0001 LECTURE 8 4
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 5
OBJECT ORIENTED
PROGRAMMING (OOP)

6.0001 LECTURE 8 6
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 7
EXAMPLE: the list [1,2,3,4]

§ 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 8
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 9
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.0001 LECTURE 8 10
DEFINE YOUR OWN TYPES

§ use the class keyword to define a new type

class ClassName:
#define attributes here
§similar to def, indent code to indicate which statements are
part of the class definition

11
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 12
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:
def init (self, x, y ):
self.x = x
self.y = y

13
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 14
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 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

def distance(self, other):


# code here

Using the class:


§ conventional way
c = Coordinate(3,4)
zero = Coordinate(0,0)
print(c.distance(zero))
HOW TO USE A METHOD

def distance(self, other):


# code here

Using the class:


§ conventional way § equivalent to
c = Coordinate(3,4) c = Coordinate(3,4)
zero = Coordinate(0,0) zero = Coordinate(0,0)
print(c.distance(zero)) print(Coordinate.distance(c, zero))
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) 19
6.0001 LECTURE 8
<3,4>
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)+">"

20
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))
21
True 6.0001 LECTURE 8
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 22
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 23
Example: Fractions
class Fraction:
def __init__(self, n, d):
self.numerator = n
if d==0:
raise Exception("Denominator cannot be 0")
else:
self.denominator = d

def __str__(self):
return str(self.numerator)+"/"+str(self.denominator)

def __add__(self, other):


f = Fraction(0,1)
f.numerator = self.numerator * other.denominator +
other.numerator * self.denominator
f.denominator = self.denominator * other.denominator
return f

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

def __eq__(self, other):


if self.numerator/self.denominator ==
other.numerator/other.denominator:
return True
else:
return False

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

§ 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 26
SUMMARY

§Object Oriented Programming


§Classes
§Objects
ACKNOWLEDGEMENT

➢ geekforgeek
➢ MIT OCW

You might also like