Session 3
Session 3
Python
Session 3
Ahmed Elaraby 1
Classes and Objects
• Python is an object oriented programming language.
• Almost everything in Python is an object, with its properties and methods.
• instance an object created from the template (an instance of the class)
• Now we can use the class named MyClass to create objects:
• p1 = MyClass()
• print(p1.x)
Ahmed Elaraby 2
The __init__() Function
• All classes have a function called __init__(), which is always executed when
the class is being initiated.
• class Person:
def __init__(self, name, age):
self.name = name
self.age = age
• p1 = Person("John", 36)
• print(p1.name) >>> John
• print(p1.age) >>> 36
Ahmed Elaraby 3
Object Methods
• Objects can also contain methods. Methods in objects are functions that
belong to the object.
• class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
• p1 = Person("John", 36)
• p1.myfunc() #Hello my name is John
Ahmed Elaraby 4
The self Parameter
• The self parameter is a reference to the current instance of the class, and is used
to access variables that belongs to the class.
• It does not have to be named self , you can call it whatever you like, but it has to
be the first parameter of any function in the class:
• class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
• p1 = Person("John", 36)
• p1.myfunc()
Ahmed Elaraby 5
• You can modify properties on objects like this:
• p1.age = 40
• class definitions cannot be empty, but if you for some reason have a
class definition with no content, put in the pass statement to avoid
getting an error.
• class Person:
pass
Ahmed Elaraby 6
Inheritance
• Inheritance allows us to define a class that inherits all the methods and properties from another
class.
• Parent class is the class being inherited from, also called base class.
• Child class is the class that inherits from another class, also called derived class.
• Any class can be a parent class, so the syntax is the same as creating any other class:
• To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:
• class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
• class Student(Person):
pass
• x = Student("Mike", "Olsen")
• x.printname() #Mike Olsen Ahmed Elaraby 7
• We want to add the __init__() function to the child class (instead of the pass
keyword).
• When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
• To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
• class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
• Python also has a super() function that will make the child class inherit all the
methods and properties from its parent:
• class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Ahmed Elaraby 8
Add Properties and Methods
• class Person:
• def __init__(self, fname, lname):
• self.firstname = fname
• self.lastname = lname
• def printname(self):
• print(self.firstname, self.lastname)
• class Student(Person):
• def __init__(self, fname, lname, year):
• super().__init__(fname, lname)
• self.graduationyear = year
• def welcome(self):
• print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
• Import the module named mymodule, and call the greeting function:
• import mymodule
• mymodule.greeting("Jonathan")
• Items are imported using from or import
• from module import function
• You can create an alias when you import a module, by using the as keyword:
• import mymodule as mx
Ahmed Elaraby 11
Built-in Modules
• There are several built-in modules in Python, which you can import
whenever you like.
• import platform
• x = platform.system()
• print(x) >>> Windows
• There is a built-in function to list all the function names (or variable names)
in a module. The dir() function:
• import platform
• dir(platform)
• print(x) >>> ['uname', 'uname_result', 'version', 'warnings', 'win32_ver‘]
Ahmed Elaraby 12
Python Datetime
• A date in Python is not a data type of its own, but we can import a module named
datetime to work with dates as date objects.
• import datetime
• x = datetime.now()
• print(x) >>> 2022-12-03 15:59:35.889368
• The date contains year, month, day, hour, minute, second, and microsecond.
• The datetime module has many methods to return information about the date object.
• The datetime object has a method for formatting date objects into readable strings.
• The method is called strftime(), and takes one parameter, format, to specify the format of
the returned string:
• print(x.year) >>> 2022
• print(x.strftime("%A")) >>> Saturday
Ahmed Elaraby 13
Directive Description Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6, 0 is Sunday 3
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version, without century 18
%Y Year, full version 2018
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%f Microsecond 000000-999999 548513
%z UTC offset +0100
Ahmed Elaraby 14
Directive Description Example
%Z Timezone CST
%j Day number of year 001-366 365
%U Week number of year, Sunday as the first day of week, 00-53 52
%W Week number of year, Monday as the first day of week, 00-53 52
%c Local version of date and time Mon Dec 31 17:41:00 2018
%C Century 20
%x Local version of date 12/31/18
%X Local version of time 17:41:00
%% A % character %
%G ISO 8601 year 2018
%u ISO 8601 weekday (1-7) 1
%V ISO 8601 weeknumber (01-53) 01
Ahmed Elaraby 15
Python Math
• Python has a set of built-in math functions, including an extensive math module,
that allows you to perform mathematical tasks on numbers.
• Python has also a built-in module called math, which extends the list of
mathematical functions.
• import math
• x = math.sqrt(64) >>> 8.0
• x = math.ceil(1.4) >>> 2
• y = math.floor(1.4) >>> 1
• x = math.pi >>> 3.141592653589793
Ahmed Elaraby 16
Python RegEx
• A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.
• RegEx can be used to check if a string contains the specified search pattern.
• Python has a built-in package called re, which can be used to work with Regular
Expressions.
• import re
• Search the string to see if it starts with "The" and ends with "Spain":
• txt = "The rain in Spain"
• x = re.search("^The.*Spain$", txt)
• .span() returns a tuple containing the start-, and end positions of the match.
• .string returns the string passed into the function
• .group() returns the part of the string where there was a match
Ahmed Elaraby 17
RegEx Functions
• findall Returns a list containing all matches.
• txt = "The rain in Spain"
• x = re.findall("ai", txt)
• print(x) >>> ['ai', 'ai']
• split Returns a list where the string has been split at each match.
• x = re.split("\s", txt)
• print(x) >>> ['The', 'rain', 'in', 'Spain']
Set Description
[arn] Returns a match where one of the specified characters (a, r, or n) is present
[a-n] Returns a match for any lower case character, alphabetically between a and n
[^arn] Returns a match for any character EXCEPT a, r, and n
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[0-9] Returns a match for any digit between 0 and 9
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case
In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character
[+]
in the string
Ahmed Elaraby 21
File Handling
• The key function for working with files in Python is the open() function.
• The open() function takes two parameters; filename, and mode.
• The open() function returns a file object, which has a read() method for reading the
content of the file:
• f = open("demofile.txt", "r")
• print(f.read())
• If the file is located in a different location, you will have to specify the file path, like this:
• f = open("D:\\myfiles\welcome.txt", "r")
• By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
• print(f.read(5))
• By calling readline() two times, you can read the two first lines:
• print(f.readline())
• print(f.readline()) Ahmed Elaraby 23
• By looping through the lines of the file, you can read the whole file, line by line:
• for x in f:
print(x)
• It is a good practice to always close the file when you are done with it.
• f.close()
• To write to an existing file, you must add a parameter to the open() function:
• f = open("demofile2.txt", "a")
• f = open("demofile3.txt", "w")
• f.write("Now the file has more content!“)
• To create a new file in Python, use the open() method, with one of the following parameters:
• f = open("myfile.txt", "x")
• f = open("myfile.txt", "w")
• f = open("myfile.txt", “a")
• To delete a file, you must import the OS module, and run its os.remove() function:
• import os
• os.remove("demofile.txt")
• To delete an entire folder, use the os.rmdir() method:
• os.rmdir("myfolder") Ahmed Elaraby 24
Types of errors
• IndexError is thrown when trying to access an item at an invalid index.
• ModuleNotFoundError is thrown when a module could not be found.
• KeyError is thrown when a key is not found.
• ImportError is thrown when a specified function can not be found.
• TypeError is thrown when an operation or function is applied to an object
of an inappropriate type.
• ValueError is thrown when a function's argument is of an inappropriate
type.
• NameError is thrown when an object could not be found.
• ZeroDivisionError is thrown when the second operator in the division is
zero.
• KeyboardInterrupt is thrown when the user hits the interrupt key
(normally Control C) during the execution of the program.
Ahmed Elaraby 25
Exception Handling
• When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
• These exceptions can be handled using the try statement:
• try:
print(x)
• except:
print("An exception occurred")
• The try block lets you test a block of code for errors.
• You can define as many exception blocks as you want, e.g. if you want to execute
a special block of code for a special kind of error:
• try:
print(x)
• except NameError:
print("Variable x is not defined")
• except:
print("Something else went wrong")
Ahmed Elaraby 26
• You can use the else keyword to define a block of code to be executed if no errors were raised:
• try:
print("Hello")
• except:
print("Something went wrong")
• else:
print("Nothing went wrong")
• The finally block, if specified, will be executed regardless if the try block raises an error or not.
• try:
print(x)
• except:
print("Something went wrong")
• finally:
print("The 'try except' is finished")