0% found this document useful (0 votes)
15 views41 pages

Python - Lecture 3

This document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, inheritance, polymorphism, encapsulation, and various types of methods (instance, class, static). It also covers special methods, tips and tricks like lambda expressions, iterators, generators, and built-in functions such as map and filter. The lecture is part of a series aimed at teaching Python programming in an easy and modular way.

Uploaded by

aaismahy
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)
15 views41 pages

Python - Lecture 3

This document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, inheritance, polymorphism, encapsulation, and various types of methods (instance, class, static). It also covers special methods, tips and tricks like lambda expressions, iterators, generators, and built-in functions such as map and filter. The lecture is part of a series aimed at teaching Python programming in an easy and modular way.

Uploaded by

aaismahy
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/ 41

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

self.name = 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
self.name = 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):
self.name = name; Man : 1

man = Human(“Ahmed”) Man2 : 0


man2 = Human(“Mohamed”)
Human : 0
man.faults = 1 Man2 : 2
print("Man :", man.faults)
Human : 2
print("Man 2:", man2.faults)
print("Human:", Human.faults) Man : 1
Human.faults = 2
print("Man 2:", man2.faults)
print("Human:", Human.faults)
print("Man :", man.faults)

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):
self.name = name
name
def speak(self):
print(“My Name is ”+self.name)
__init__()
man = Human(“Ahmed”)
man.speak() 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):
self.name = name name

@classmethod
__init__()
def makeFaults(cls):
cls.faults +=1
makeFaults()
print(cls.faults)
Human.makeFaults() #1
man = Human(“Ahmed”)
man.makeFaults() #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
self.name = name

__init__()
@staticmethod
def measureTemp(temp):
if (temp == 37): measureTemp()
return “Normal”
return “Not Normal”

Human.measureTemp(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”)

Human.walk() Human.sleep()

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):
self.name = name Human Class
def speak(self):
print(“My Name is ”+self.name);
class Employee(Human):
def __init__(self, name, salary):
super(Employee, self).__init__(name)
self.salary = salary
def work(self):
print(“I’m working now”);
Employee
emp = Employee(“Ahmed”, 500)
Class
emp.speak()
emp.work()
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
self.name = name
def speak(self):
print(“My Name is ”+self.name);
class Employee(Human):
def __init__(self, name, salary):
super(Employee, self).__init__(name)
self.salary = salary
def speak(self):
print(“My salary is ”+self.salary);
Employee
emp = Employee(“Ahmed”, 500) Class
emp.speak() #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(man.getName())
#output: Mahmoud

Open Source Department – ITI


Encapsulation
@property
class Human:
def __init__(self, age):
self.age = age

@property
def age(self):
return self.__age

@age.setter
def age(self, age):
if age > 0:
self.__age = age
if age <= 0:
self.__age = 0

man = Human(23)
print(man.age) # 23
man.age = -25
print(man.age) # 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):
self.name = name

def __str__(self):

return “Hi, I’m Human and my name is ”+ self.name

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):
self.name = 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):
self.legs = legs

def __len__(self):

return self.legs

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

You might also like