View
50
Download
1
Category
Preview:
Citation preview
Fundamentals of Programming(Python)
Object-Oriented Programming
Sina SajadmaneshSharif University of Technology
Fall 2017
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
2SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
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
3SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
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
4SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
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
5SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
Defining ClassesClass header ◦ Keyword class begins definition
◦ Followed by name of class and colon ( : )
Initializer method __init__◦ Executes each time an object is created
◦ Initialize 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
6SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
Working with ObjectsInstantiating objects:
Accessing objects’ attributes:
8SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
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)
Adding Methods
11SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
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
12SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
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
13SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
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
14SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
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
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
17SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
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 a another custom method
18SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
>>> p = Point(2,3)
>>> q = Point(2,3)
>>> p == q
False
SamenessDeep Equality
19SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
>>> 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
20SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
>>> 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
21SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
>>> 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
22SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
CopyingDeep Copy◦ Copies the object, and recursively copies the embedded objects
23SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
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
24SINA SAJADMANESH - FUNDAMENTALS OF PROGRAMMING [PYTHON]Fall 2017
>>> 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
Recommended