Python: The Easy Way
Lecture 3
Object Oriented Python
OO Python
Intro
Modules
Object Oriented
Functions Level
Modular Level
Procedural
Level
Speghatti Level
Open Source Department – ITI
OO Python
Intro
height = 175 cm velocity = 200 m/s
weight = 76 kg Properties brakes = 2
walk() stop()
speak() Methods move()
ride( BikeObj )
Man Object Bike Object
Open Source Department – ITI
OO Python
OOP Keywords
OOP Keywords
Class
A class is a template definition of an object's properties and methods.
class Human: Human Class
pass
Open Source Department – ITI
OOP Keywords
Object
An Object is an instance on a Class.
class Human: Human Class
pass
man = Human()
Man Object
Open Source Department – ITI
OOP Keywords
Constructor
Constructor is a method called at the moment an object is instantiated.
class Human: Human Class
def __init__(self):
print(“Hi there”) __init__()
man = Human()
Output:
Hi there
Man Object
Open Source Department – ITI
OOP Keywords
Instance Variable
Instance Variable is an object characteristic, such as name.
class Human: Human Class
def __init__(self, name): name
[Link] = name
__init__()
man = Human(“Ahmed”)
Name is Ahmed
Man Object
Open Source Department – ITI
OOP Keywords
Class Variable
Class Variable is the variable that shared by all instances.
class Human: Human Class
makeFault = True makeFault = True
def __init__(self, name):
name
[Link] = name;
man = Human(“Ahmed”)
man2 = Human(“Mohamed”) __init__()
Name is Ahmed Name is Mohamed
He makes faults He makes faults
Open Source Department – ITI
OOP Keywords
Class Variable
class Human: Output:
faults = 0
def __init__(self, name):
[Link] = name; Man : 1
man = Human(“Ahmed”) Man2 : 0
man2 = Human(“Mohamed”)
Human : 0
[Link] = 1 Man2 : 2
print("Man :", [Link])
Human : 2
print("Man 2:", [Link])
print("Human:", [Link]) Man : 1
[Link] = 2
print("Man 2:", [Link])
print("Human:", [Link])
print("Man :", [Link])
Open Source Department – ITI
OOP Keywords
Instance Method
Instance Method is an object capability, such as walk.
class Human: Human Class
def __init__(self, name):
[Link] = name
name
def speak(self):
print(“My Name is ”+[Link])
__init__()
man = Human(“Ahmed”)
[Link]() speak()
My Name is Ahmed
Open Source Department – ITI
OOP Keywords
Class Method
Class Method is a method that shared by all instances of the Class
class Human: Human Class
faults=0 faults
def __init__(self, name):
[Link] = name name
@classmethod
__init__()
def makeFaults(cls):
[Link] +=1
makeFaults()
print([Link])
[Link]() #1
man = Human(“Ahmed”)
[Link]() #2
Open Source Department – ITI
OOP Keywords
Static Method
Static Method is a normal function that have logic that related to the Class
class Human: Human Class
def __init__(self, name):
name
[Link] = name
__init__()
@staticmethod
def measureTemp(temp):
if (temp == 37): measureTemp()
return “Normal”
return “Not Normal”
[Link](38) # Not Normal
Open Source Department – ITI
OOP Keywords
Static vs Class Methods
Class Method Static Method
# cls(Class) is implicity # Static Method is like a
passed to class method like normal function but we put it
self(instance) in instance in the class because it have
method. logic that related to the
class.
# Class Method is related
to the class itself. # We call it Helper Method
class Human: class Human:
@classmethod @staticmethod
def walk(cls): def sleep():
print(“Walk …”) print(“whoa”)
[Link]() [Link]()
Open Source Department – ITI
OO Python
OOP Concepts
OOP Concepts
Inheritance
Inheritance
Intro
Human
Class
Employee
Class
Engineer Teacher
Class Class
Open Source Department – ITI
Inheritance
Example
class Human:
def __init__(self, name):
[Link] = name Human Class
def speak(self):
print(“My Name is ”+[Link]);
class Employee(Human):
def __init__(self, name, salary):
super(Employee, self).__init__(name)
[Link] = salary
def work(self):
print(“I’m working now”);
Employee
emp = Employee(“Ahmed”, 500)
Class
[Link]()
[Link]()
Open Source Department – ITI
Inheritance
Multiple Inheritance
Python supports Multiple Inheritance
Report**:
Human Mammal
1- How super Function handle Multiple Inheritance.
Class Class
2- If Human and Mammal Have the same method
like eat but with different Implementation. When
Child [Employee] calls eat method how python
Employee handle this case.
Class
**Prove your opinion with examples.
Open Source Department – ITI
OOP Concepts
Polymorphism
Polymorphism
Intro
Poly means "many" and morphism means "forms". Different classes might define
the same method or property.
Eagle Fly() I fly very fast
Bird class Dove Fly() I fly for long distances
Fly()
I fly Penguin Fly() I can’t fly
Open Source Department – ITI
Polymorphism
Method Overriding
class Human:
def __init__(self, name):
Human Class
[Link] = name
def speak(self):
print(“My Name is ”+[Link]);
class Employee(Human):
def __init__(self, name, salary):
super(Employee, self).__init__(name)
[Link] = salary
def speak(self):
print(“My salary is ”+[Link]);
Employee
emp = Employee(“Ahmed”, 500) Class
[Link]() #My Salary is 500
Open Source Department – ITI
Polymorphism
Method Overloading
Report**:
Can we do overloading in Python ?
If Yes, Tell me How??
If No, Tell me Why??
** Support Your Answer by Examples.
Open Source Department – ITI
OOP Concepts
Encapsulation
Encapsulation
intro
Encapsulation is the packing of data and functions into one component (for
example, a class) and then controlling access to that component .
getName()
Class
amigos
Open Source Department – ITI
Encapsulation
Example
class Human:
def __init__(self, name):
self.__name = name
def getName(self):
return self.__name
man = Human(“Mahmoud”)
print(man.__name)
AttributeError: 'Human' object has no attribute ‘__name’
print([Link]())
#output: Mahmoud
Open Source Department – ITI
Encapsulation
@property
class Human:
def __init__(self, age):
[Link] = age
@property
def age(self):
return self.__age
@[Link]
def age(self, age):
if age > 0:
self.__age = age
if age <= 0:
self.__age = 0
man = Human(23)
print([Link]) # 23
[Link] = -25
print([Link]) # 0
Open Source Department – ITI
Special Methods
Special Methods
__str__
Special Method that controls how Object treats as printable
class Human:
def __init__(self, name):
[Link] = name
def __str__(self):
return “Hi, I’m Human and my name is ”+ [Link]
man = Human(“Ahmed”)
print(man)
#output: <__main__.Human object at 0x000000FD81804400>
print(man)
#output: Hi, I’m Human and my name is Ahmed
Open Source Department – ITI
Special Methods
__call__
Special Method that controls how Object can show as callable
class Human:
def __init__(self, name):
[Link] = name
def __call__(self):
print(“You called me !”)
man = Human(“Ahmed”)
man()
#output: TypeError: 'Employee' object is not callable
man()
#output: You called me !
Open Source Department – ITI
Special Methods
__len__
Special Method that controls when measure the Object length
class Animal:
def __init__(self, legs):
[Link] = legs
def __len__(self):
return [Link]
dog = Animal(4)
len(dog)
#output: TypeError: 'Employee' object has no len()
len(dog)
#output: 4
Open Source Department – ITI
Tips and Tricks
Tips and Tricks
Lambda Expressions
Lambda Expressions are used to make anonymous functions
lambda input:output
Example
lmdaFn = lambda x:x+4
lmdaFn(3) #7
def sumFn(n):
return lambda x:x+n
sumFn(5) #<function ….>
sumFn(5)(4) #9
Open Source Department – ITI
Tips and Tricks
Iterators (iter and next)
iter is used to generate an iterator from iterable.
next is used to return the next iteration from iterators.
Example
l = [“JavaScript”, “Python”, “Java”] # iterable
it = iter(l) # convert iterable to iterator
next(it)
#output: “JavaScript”
next(it) #output: “Python”
next(it) #output: “Java”
Open Source Department – ITI
Tips and Tricks
Generators
It is used to generate iterators
Example
def nonGenFn(): def genFn():
for i in range(5): for i in range(5):
return i yield i
ng = nonGenFn() g = genFn()
next(ng) next(g) #output: 0
TypeError: ‘int' object is next(g) #output: 1
not an iterator
Open Source Department – ITI
Tips and Tricks
map Function
map(function, sequence)
Map function are used to make iterables from apply the given function on every
item in the given sequence
Example
it = map(lambda x:x+4, [1,3,5])
for i in it:
print(i)
# 4
# 7
# 9
Open Source Department – ITI
Tips and Tricks
filter Function
filter(condfunction, sequence)
Filter function are used to make iterables from filter each item in the given
sequence by the given function
Example
it= filter(lambda x:x%5==0, [-15, -8, -5, 3, 5, 9, 25])
for i in it:
print(i, end=“, ”)
# -15, -5, 5, 25
Open Source Department – ITI
What’s Next ?
What’s Next
Frameworks and Libraries
Thank You