Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Lecture 8 - Object Oriented Programming

Uploaded by

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

Lecture 8 - Object Oriented Programming

Uploaded by

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

ENG 202: Computers and Engineering

Object Oriented Programming in PYTHON


LECTURE 8 – Object Oriented Programming

Maurice J. KHABBAZ, Ph.D.


Objects
• So far, known data types: int, float, str, list, tuple, dict:
• Examples of objects of these types:
1234 2.1 “hi” [1,2] (1,2) {‘A’:1, ‘B’:3}
• Each object has:
• A type.
• An internal data representation (primitive/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.
• “hi” is an instance of an str.

Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 2


Object Oriented Programming (OOP)
• Everything in PYTHON is an object (and has a type).
• It is possible to:

• Create new objects of some type.

• Manipulate objects.

• Destroy objects:
• Explicitly using del or just “forget” about them.
• Destroyed/inaccessible are “garbage” and will be reclaimed through “garbage collection”.

Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 3


What Are Objects?
• They constitute data abstractions that capture:

1. An internal representation (through data attributes)

2. An interface for interacting with the abstracted object:


• Through methods (a.k.a. procedures/functions) that:
• Define behaviors.
• Hide implementations.

Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 4


Example: Lists
• Q: How are lists represented internally?
• A: Linked sequence of cells. A part of
L = [1, 2, 3, 4] Memory

L 1 2 3 4
Follow pointer
to next index
• Q: How to manipulate lists?
• A: 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().
• Internal Representation (IR) should be private.
• Correct behavior compromised if IR manipulated directly.
Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 5
Advantages of OOP
• Bundle data into packages:
• Values + procedures to work on them through well-defined interfaces.
• Divide-and-Conquer development:
• Implement and test behavior of each class/object separately.
• Increased modularity reduces complexity.
• Similar to functions, classes make is easy to reuse code:
• Many PYTHON modules define new classes.
• Each class has a separate environment (no collision).
• Inheritance allows subclasses:
• To re-define/extend a selected subset of a superclass’ behavior.

Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 6


Custom-Built Types Using Classes
• Distinguish between:

• Creating a class:
• Defining the class’ name.
• Defining the class’ attributes.

• Using an instance of the class:


• Creating new instances of objects of this type (i.e. instantiating objects)
• Performing operations on the newly created instances.

Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 7


Define Custom-Built Types
• class keyword is used to define a new type:
ss
cla ition name/type parent class
efin class Coordinate(object):
d
# define attributes here

• Similar to def, indent code to indicate statements belonging to class definition.

• object implies that Coordinate is a PYTHON object:


• It inherits all pre-defined attributes of PYTHON object class:
• Coordinate is a subclass of object.
• object is a superclass of Coordinate
Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 8
Attributes
• They are data and methods that belong to the class.
• Data Attributes:
• Think of them as other objects that make up the class.
• Example: a coordinate is made up of two numbers.
• Methods (procedural attributes):
• Think of them as functions that only work with their defining class.
• Used to interact with objects of this type/class.
• Example:
• Distance between two Coordinate objects makes sense.
• Distance between two list objects has no meaning.

Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 9


Creating A Formal Instance Of A Class
• A special method __init__() is used to:
s
• Initialize some data attributes. lize ect
n itia obj
at i te
a th ina
t
class Coordinate(object): da ord
C o
a
def __init__(self, x, y):
o
self.x = x
t
h o d ce
t re self.y = y
me tan sco
al n ins der to par
c i an am
spe ate a le un ins et
cre doub data attributes for tan er t
sa ce o r
i every Coordinate object of efe
__ the r
cla
ss
Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 10
Creating An Actual Instance Of A Class
r di n ate
w Coo
• Example: creat e a n e
d pass 3 a n d 4 as
ob je c t an
i n i t __()
__
c = Coordinate(3, 4) parameters to
origin = Coordinate(0, 0) t to ac cess
do
use the of instance c
bute
print(c.x) an attri
print(origin.x)

• Data attributes of an instance referred to as instance variables.


• self in definition requires no actual parameter:
• PYTHON takes care of it automatically.

Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 11


Methods
• Procedural attributes:
• Functions that work only with their defining 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 dot (i.e. “.”) operator is used to access any attribute:


• A data attribute of an object.
• A method of an object.

Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 12


Example: Define A Method For Coordinate
class Coordinate(object):
def __init__(self, x, y): t h od
e to me
an c er
self.x = x in st et
ta
a ny a ram d a
self.y = y efers to th er p c c ess
r an o n to a
tatio
def distance(self, other): o t no
d
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 as any typical function.
Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 13
Using A Method
t h od
me ition
in
def distance(self, other): def
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

Conventional Usage 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))
n o t g an
o call of ters elf f f l u
n
d i h od
c t t on e e
a m n g s ie d eo eo in c et
je
ob thod nam thod a r
P udi pl
m
na ass m
na thod e
rs
te ll the self
m
me me l
in c f is i m cl me a ram o ca ting
l c) P ct t sen
e e e
( s to b obj repre
Saturday, March 9, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. on 14
Print Representation Of An Object
>>> c = Coordinate(3,4)
>>> print(c)
<__main__.Coordinate object at 0x7fa91

• Quite uninformative default print representation.


• Define a new __str__() method for a class:
• PYTHON calls this method when attempting to print object using print.
• Custom-build this method to display informative details on the screen.
• Example:
>>> print(c)
<3, 4>
Saturday, March 9, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 15
Defining Custom-Built Object 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 tu rn
e
u st r ing
def __str__(self): m str
a
e of d return “<”+str(self.x)+“,”+str(self.y)+“>”
am n tho e
l m
cia
spe
Saturday, March 9, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 16
Wrapping Up Types And Classes
• Interest may be in revealing the type of an object instance:
>>> c = Coordinate(3,4)
>>> print(c)
<3, 4> return of the __str__() method
>>> print(type(c))
<class __main__.Coordinate> type of object c is of class Coordinate
• This makes sense since:
>>> print(Coordinate)
<class __main__.Coordinate> Coordinate is a class
>>> print(type(Coordinate))
<type ‘type’> a Coordinate class is a type of object
• Use isinstance() to check if an object is of a certain type:
>>>print(isinstance(c, Coordinate))
True

Saturday, March 9, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 17


Special Operators
• +, -, ==, <, >, len(), print and many others:
https://docs.python.org/3/reference/datamodel.html#basic-customization
• Similar to print(), can override these to work with custom-built 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

… among others …

Saturday, March 9, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 18


The Power Of OOP
• Bundle together objects that share:
• Common attributes.
• Procedures that operate on those attributes.
• Use abstraction to make a distinction between:
• Object implementation.
• Object usage.
• Build layers of object abstractions that inherit behaviors from other
classes/objects.
• Create custom-built object classes on top of PYTHON’s basic classes.

Saturday, March 9, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 19


Friday, March 8, 2019 NDU - ENG 202 - Maurice J. KHABBAZ, Ph.D. 20

You might also like