2. AGENDA
Deep into
◈ Exception Handling
◈ Modules, Packages
OOP
◈ Key words
◈ Concepts
Data base
◈ MySQLdb Module
Other
◈ Regular Expression
◈ Clean code
◈ Lab
4. Exception Handling Continue
◈ Error in syntax
eval(“26”
syntaxError: Missing ‘)’
◈ Error during execution are called Exceptions
print firstname
NameError: name ‘firstname’ is not defined
5. Exception Handling Continue
try:
#operations goes here.
except Exception_type_1:
#if Exception_type_1 happened execute this code.
except Exception_type_2 as e:
#if Exception_type_2 happened print(e)
else:
#if there is no exceptions execute this code.
finally:
#execute this code at any case.
10. Module
Raising Modularity main purposes is reusability enrichment.
Creating python files and importing their functions
From greeting import hi, bye
hi()
bye()
greeting.py
_______________
def hi():
print “hi”
def bye():
print “bye”
11. Package
Putting similar modules into directory containers folders
Package folder must contain a file named __init__.py to tell that this folder
will contain python modules.
We can override __all__ list to specify which properties should be exposed to *
in the API
__all__ = [“hi”, “bye”]
From human.greeting import *
hi()
bye()
greeting.py
_______________
def hi():
print “hi”
def bye():
print “bye”
18. Instance Variables
class Human():
def __init__(self, name):
self.name = name
man = Human(“Mohamed”)
Human Class
An Object characteristic, such as the name, weight, ...
man object
__init__()
name
Mohamed
19. Class Variables
class Human():
working = True
def __init__(self, name):
self.name = name
man = Human(“Mohamed”)
women = Human(“Mona”)
Human Class
A Class variable is the variable shared by all instances.
He works
__init__()
working
Mohamed
name
She works
Mona
21. Instance Method
class Human():
def __init__(self, name):
self.name = name
def speak(self):
print “My name is”, self.name
# Object passed implicitly to instance method self
man = Human(“Mohamed”)
man.speak()
Human Class
An Instance method is an object capability like walk, talk, ..
man object
__init__()
Speak()
name
My name is Mohamed
22. Class Method
class Human():
fault = 0
def __init__(self, name):
self.name = name
@classmethod
def makesfault(clas):
clas.fault += 1
print clas.fault
Human.makesfault() #1
Man = Human(“Ali”)
Man2 = Human(“Ahmed”)
Man.makesfault() #2
Man2.makesfault() #3
Human Class
A Class method is that method shared by all instances.
__init__()
fault
name
makesfault()
23. Static Method
class Human():
def __init__(self, name):
self.name = name
@staticmethod
def tempmeasure(temp):
if temp == 37:
print “Normal”
print “Not Normal”
Human.tempmeasure(38) # Normal
Human Class
It is a normal function has logic related to the class.
__init__()
name
tempmeasure()
24. Class Method VS Static Method
# Cls (class) is implicitly passed to
class method as well as self(object) in
instance method.
# Class method is related to the class
it self we don’t call class method
using instances.
class Human:
@classmethod
def walk(cls):
print “walking”
Human.walk()
# A normal function has logic related
to the class.
# Doesn’t have any implicitly passed
arguments.
# Can be called by both class and
instance.
# We call it helper methods.
class Human:
@staticmethod
def walk():
print “walking”
Human.walk()
28. Super is used to call the parent class without knowing its name.
#inheritance
#super
class SubClass(ParentClass):
def __init__(self):
ParentClass.__init__(self)
class SubClass(ParentClass):
def __init__(self):
super(SubClass, self).__init__()
29. class Human():
def __init__(self, name):
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 work(self):
print “I’m working now”
emp = Employee(“Ahmed”, 1000)
emp.speake()
emp.work()
Human
Employee
#inheritance
30. Report
Python Supports Multiple Inheritance
1. How super function handle multiple inheritance.
2. If Human and Mammal have same method eat but with different implementation,
when child Employee calls eat method how python handle this case.
Prove your opinion with example.
Mail report to djangoteamiti@gmail.com
Subject: “Report #2 – Name – sheet number”
# Multiple inheritance
Human Mammal
Employee
32. Poly means “Many” morphism means “Forms”. Different classes might define the same
method or property.
#polymorphism
#intro
Bird Class
Fly()
Eagle Fly()
Dove Fly()
Penguin Fly()
I fly very fast
I fly for long distances
I can’t fly
I fly ☺
33. class Human():
def __init__(self, name):
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
emp = Employee(“Ahmed”, 1000)
emp.speake()
Human
Employee
# Method overriding
>> My salary is 500
34. Report
Can we do overloading in python ?
1. If Yes, Tell me how
2. If No, Tell me why
Support your Answer by example.
Mail report to djangoteamiti@gmail.com
Subject: “Report #3 – Name – sheet number”
# Method overloading
36. Encapsulation is packing data and functions into one component “a class for example”
and then controlling access to that component.
#encapsulation
#intro
Class
“Mohamed”
getName()
Private variable can be defined by setting double __ before its name
Then it is only visible inside the class
37. class Human():
def __init__(self, name, age):
self.__name = name #private __name
self.age = age
def getName(self):
return “My name is ” + self.__name
emp = Employee(“Ahmed”, 30)
print emp.age
print emp.__name
print emp.getName()
#encapsulation
>> 30
>> AttributeError: ‘Human’ object has no attribute ‘__name’
40. First of all we need MySQLdb module that enabling issuing and executing sql.
Steps:
• Import MySQLdb module.
• Acquire connection to the database.
• Create cursor (SQL executor).
• Execute sql
- Commit for insert and delete
- fetch for select
- rollback for exception
• Close connection.
#intro
41. On python shell
>> import MySQLdb
>>
# No news is a good news
Else, install the module
>> sudo apt-get install python-mysqldb
#Database
42. # Get Connection
import MySQLdb
db = MySQLdb.connect(“Host”, “user”, “password”, “db name”)
# Get Cursor executor
cursor = db.cursor()
# Execute sql using cursor
Cursor.execute(sql string)
#Database
43. READ Operation on any database means to fetch some useful information from the
database.
fetchone() It fetches the next row of a query result set. A result set is an object
that is returned when a cursor object is used to query a table.
fetchall() It fetches all the rows in a result set. If some rows have already been
extracted from the result set, then it retrieves the remaining rows from the result set.
Rowcount This is a read-only attribute and returns the number of rows that were
affected by an execute() method.
#Database
44. First create a new database called “mytestdb” in MySQL
for testing
import MySQLdb
db = MySQLdb.connect("localhost","root","admin","mytestdb")
cursor =db.cursor()
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data =cursor.fetchone()
print"Database version : %s “ % data
db.close()
#Database
#fetchone()
45. import MySQLdb
db = MySQLdb.connect("localhost","root","admin","mytestdb")
cursor =db.cursor()
sql_str1= “select * from employee”
try:
cursor.execute(sql_str1)
results = cursor.fetchall()
for result in results:
print result[0] #id
print result[1] #name
except:
db.rollback()
db.close()
#Database
#fetchall()
47. Regular Expression
Python module re has many functions
Match() # check for entire matching
Search() # checks for any matching
import re
ptrn = r’^[a-zA-z0-9]+@[a-z]+.[a-z]{2,4}$’
email = ‘mohamedramadan@ibm.com’
Result = re.match(ptrn, email)
If result:
print “Welcome”, result.group()
else:
print “Invalid email”
50. Implement Employee methods
sleep(hours): Method in Person class( 7 happy, <7 tired, >7 lazy)
eat(meals): Method in Person class( 3 meals 100 health rate, 2 meals
75 health rate , 1 meal 50 health rate)
buy(items): Method in Person class( 1 Item decrees Money 10 LE)
sendEmail(to, suject, body receiver_name): on call it creates a
file represent the email.
51. Implement Employee methods cont…
work(hours): Method in Employee class( 8 happy, > 8
tired, > 8 lazy)
Salary: Property must be 1000 or more
Health rate: Property must be between 0 and 100
Email: Property must be verified
52. Implement Office methods
get_all_employees(): Method in Office class get all current employees
get_employee(empId): Method in Office class get employee data of given
employee id, and if a manager display all info except salary.
hire(Employee): Method in Office class hires the given employee
fire(empId): Method in Office class fires the given employeeid
DB table Employee should maintain employee objects and office retrievals
53. Let the program be user command interface.
Print a menu with the functionalities allowed. For example
For adding new employee enter “add”
If manager press “m” if normal employee press “3”
Enter your data:
>> Name:
>> age:
The final menu option is “q” to quit the application.