Fundamentals of Programming(Python)
Object-Oriented Programming
Ali TaheriSharif University of Technology
Spring 2019
Outline1. Python Data Types
2. Classes and Objects
3. Defining Classes
4. Working with Objects
5. Customizing Initializer
6. Adding Methods
7. Special Methods
8. Composition
9. Mutability
10.Sameness
11.Copying
2ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
Python Data TypesSo far we have seen several data types in Python
Some of these data types are primitive data types◦ Integer, Float, String, Boolean
Some of them are more complicated◦ List, Dictionary, Set, File
In Python, we can build our own data types◦ Using the other available types
◦ This is the subject of Object-Oriented programming
3ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
Classes and ObjectsAn object is simply a variable
A Class is simply a data type of an object
We have been using objects!◦ Just didn’t call them objects
For example: str is a data type (or class)◦ We created objects of type (class) string
4ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
animal = "cow"
fruit = "apple"
Classes and ObjectsObject vs Variable◦ Objects may contain variables, called attributes
◦ Objects may contain methods
Class vs Type◦ Programmer can define his own classes
◦ Attributes and methods are defined within class
5ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
Defining ClassesClass header ◦ Keyword class begins definition
◦ Followed by name of class and colon ( : )
Initializer method __init__◦ Executes each time an object is created
◦ Initializes attributes of class
Object reference◦ All methods must at least specify this one parameter
◦ Represents object of class from which a method is called
◦ Called self by convention
6ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
Defining Classes
7ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
Working with ObjectsInstantiating objects:
Accessing objects’ attributes:
8ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
p = Point()
q = Point()
p.x = 3
q.x = p.y + 5
q.y = p.x * q.x
print(p.x, p.y, q.x, q.y)
Customizing Initializer
9ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
Adding Methods
10ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
Adding Methods
11ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distance_from_origin(self):
return ((self.x**2) + (self.y**2)) ** 0.5
def distance(self, other):
dx = self.x - other.x
dy = self.y - other.y
return (dx**2 + dx**2) ** 0.5
p = Point(2, 6)
q = Point(-1, 4)
d = p.distance(q)
print(d)
Special Methods
12ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
Operator Method Description
+ __add__(self, other) Addition
- __sub__(self, other) Subtraction
* __mul__(self, other) Multiplication
/ __truediv__(self, other) Division
< __lt__(self, other) Less than
<= __le__(self, other) Less that or equal
> __gt__(self, other) Greater than
>= __ge__(self, other) Greater than or equal
== __eq__(self, other) Equal to
!= __ne__(self, other) Not equal to
Special Methods
13ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
Operator Method Description
[index] __getitem__(self, index) Index operator
in __contains__(self, value) Check membership
len __len__(self) The number of elements
str __str__(self) The string representation
Special Methods
14ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return '(%d,%d)' % (self.x, self.y)
def __getitem__(self, index):
if index == 0:
return self.x
elif index == 1:
return self.y
else:
raise IndexError('Point index out of range.')
>>> p = Point(2,3)
>>> print(p)
(2,3)
>>> print(p[1])
3
Composition
15ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
Mutability
16ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
SamenessWhen dealing with objects, the concept of sameness can be ambiguous◦ Do the two objects contain the same data?
◦ Do they represent the same object?
Shallow Equality◦ Only compares the references, not the contents of the objects
17ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
SamenessThe equality operator (==) performs shallow equality check by default on user-defined classes◦ Unless the __eq__() method is implemented
Deep Equality◦ Compares the contents of the objects
◦ Must be implemented manually through __eq__() or another custom method
18ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
>>> p = Point(2,3)
>>> q = Point(2,3)
>>> p == q
False
SamenessDeep Equality
19ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
>>> p = Point(2,3)
>>> q = Point(2,3)
>>> p == q
True
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __eq__(self, other):
return (self.x == other.x and
self.y == other.y)
CopyingThe assignment operator make aliases◦ Changing one results in changing the other
◦ What if we want separate duplicates?
We can copy objects using the copy module◦ Shallow copy
◦ Deep copy
20ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
>>> p = Point(2,3)
>>> q = p
>>> p is q
True
CopyingThe assignment operator make aliases◦ Changing one results in changing the other
◦ What if we want separate duplicates?
We can copy objects using the copy module◦ Shallow copy
◦ Deep copy
21ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
>>> p = Point(2,3)
>>> q = p
>>> q.x = 5
>>> print(p)
(5,3)
CopyingShallow Copy◦ Copies the object, but doesn’t copy the embedded objects unless
they are immutable
22ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
CopyingDeep Copy◦ Copies the object, and recursively copies the embedded objects
23ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
class Rectangle:
""" A class to manufacture rectangle objects """
def __init__(self, corner, w, h):
self.corner = corner
self.width = w
self.height = h
def __eq__(self, other):
return (self.corner == other.corner and
self.width == other.width and
self.height == other.height)
CopyingDeep Copy◦ Copies the object, and recursively copies the embedded objects
24ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON]Spring 2019
>>> import copy
>>> r = Rectangle(Point(1,4), 7, 2)
>>> s = copy.copy(r)
>>> r == s
True
>>> s.corner.x = 5
>>> r == s
True
>>> t = copy.deepcopy(r)
>>> r == t
True
>>> t.corner.x = 6
>>> r == t
False