Python Basics Session4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

‫الجمهورية العربية السورية‬

‫المعهد العالي للعلوم التطبيقية والتكنولوجيا‬

‫دورة لغة البايثون في مجال تطبيقات الذكاء الصنعي ‪ /‬التعلم اآللي ‪ /‬التعلم العميق ‪ /‬الحقيقة المعززة‬

‫‪Python Programming Language for Applications of Artificial‬‬


‫‪intelligence, Machine learning, Deep learning, and Augmented reality‬‬

‫)‪Session 4 (OOP ctd .. / Modules / numpy / Exercises‬‬

‫م‪ .‬علي خضور‬ ‫ما‪ .‬وسام شريفة‬ ‫د‪ .‬وسيم صافي‬

‫‪10/10/2023‬‬

‫‪1‬‬
‫الجمهورية العربية السورية‬
‫المعهد العالي للعلوم التطبيقية والتكنولوجيا‬

1- Object Oriented Programming:


Class / Object /
Class Constructor /
Methods on Objects /
Converting Objects to Strings __str__
Comparing Objects
Class Methods and Static Methods
Overloading / Overriding
Inheritance
Properties

2
‫الجمهورية العربية السورية‬
‫المعهد العالي للعلوم التطبيقية والتكنولوجيا‬

2- Modules and Packages:


Importing Modules
Creating a Module
Standard packages (math / random / time / datetime / os / )

3) numpy Module

3
‫الجمهورية العربية السورية‬
‫المعهد العالي للعلوم التطبيقية والتكنولوجيا‬

1- Object Oriented Programming:


Class / Object /
Class Constructor /
Methods on Objects /
Converting Objects to Strings __str__
Comparing Objects
Class Methods and Static Methods
Overloading / Overriding
Inheritance
Multiple Inheritance
Properties

4
Class Variables:
Have the same value for all instances of a
1) Object Oriented Programming (OOP) : class:
Class Data Members: class Point :
class Point : count = 0 # Count all point objects
count = 0 # Count all point objects def __init__ (self , x, y):
def __init__ (self , x, y): Point.count += 1
self.count += 1 print(self.count)
print(self.count)
p1 = Point(1,2)  1
p1 = Point(1,2) 1 print(p1.count)  1
print(p1.count) 1
p2 = Point(1,2)  2
p2 = Point(1,2) 1 print(p2.count)  2
print(p2.count) 1

5
1) Object Oriented Programming (OOP) :
Class Methods and Static Methods
class Spam :
spam = "I don ’t like spam ."
def foo(self):
print("foo")
@classmethod
def cmethod (cls):
print(cls.spam )
@staticmethod
def smethod ():
print(" static method .")

a= Spam()
a.foo()

Spam.cmethod ()
Spam.smethod ()

s = Spam()
s. cmethod() # no usually used
s. smethod() # no usually used
6
1) Object Oriented Programming (OOP) :
Properties:
class Spam:
def __init__ ( self ):

self._value = 0 # tradition for private


def get_value ( self ):
return self._value

def set_value (self , value ):


if value <= 0:
self._value = 0
else:
self._value = value

value = property ( get_value , set_value )


s = Spam ()
print(s._value)
s.value = 6
print(s.value)
s.value = -6
print(s.value)
7
1) Object Oriented Programming (OOP) :
Inheritance:
class Phone :
def call ( self ):
print(“call”)
class MobilePhone ( Phone ):
def send_text ( self ):
print(“send text”)

h = MobilePhone ()
h. call () # inherited from Phone
h. send_text () # own method

8
1) Object Oriented Programming (OOP) :
- Overloading in Python : )‫(التحميل الزائد ) (فرط التحميل‬
Two or more methods have the same name but different numbers of parameters or
different types of parameters, or both. These methods are called overloaded methods
and this is called method overloading.

The problem with method overloading in Python is that we may overload the methods
but can only use the latest defined method.

def product(a, b):


p=a*b
print(p)

def product(a, b, c):


p=a*b*c
print(p)

#product(4, 5) # error
product(4, 5, 5)

9
1) Object Oriented Programming (OOP) :
- Overloading in Python : Solutions: 1
def add(datatype, *args):
# if datatype is int
if datatype == 'int':
answer = 0

if datatype == 'str':
answer = ''

# Traverse through the arguments


for x in args:
answer = answer + x
print(answer)

# Integer
add('int', 5, 6)

# String
add('str', 'Hello ', ‘ World') 10
1) Object Oriented Programming (OOP) :
- Overloading in Python : Solutions: 2

def print_values(a=None, b=None):


# Checks if both parameters are available
if a != None and b == None:
print(a)
else:
print(a+b)

print_values(2, 3)
print_values(2)

11
‫الجمهورية العربية السورية‬
‫المعهد العالي للعلوم التطبيقية والتكنولوجيا‬

2- Modules and Packages:


Importing Modules
Creating a Module
Standard packages (math / random / time / datetime / os / )

12
2) Modules:

Importing Modules:

- Functions, classes and object thematically belonging together are grouped in


modules.
import math
s = math . sin( math .pi)

import math as m
s = m.sin(m.pi)

from math import pi as PI , sin


s = sin(PI)
from math import *
s = sin(pi)

import math
print(dir(math))
print(help(math))
13
2) Modules:

Creating Modules:

""" My first module : my_module .py """


def add(a, b):
""" Add a and b."""
return a + b
print (add (2, 3))

main.py
import my_module 5
print(my_module.add (1 , 2)) 3

Top level instructions are executed


during import!
14
2) Modules:

Creating Modules:
If instructions should only be executed when running as a script, not importing it:
def add(a, b):
return a + b

if __name__ == "__main__":
print (add (2, 3))

main.py
import my_module 
print(my_module.add (1,2)) 3

15
2) Modules:

math:
Constants: e , pi
Exponential function: exp(x)
Logarithm: log(x[, base]) , log10(x)
Power and square root: pow(x, y) , sqrt(x)
Trigonometric functions: sin(x) , cos(x) , tan(x)
Conversion degree $ radiant: degrees(x) , radians(x)

random:
Random integers: randint(a, b)

Random floats: random()

Shuffled sequence: shuffle(seq[, random])

import random
s = [1, 2, 3, 4, 5]
print(s)
random.shuffle(s)
print(s)
16
2) Modules:

time/ datetime:

import datetime
d1 = datetime . date (2008 , 3, 21)
d2 = datetime . date (2008 , 6, 22)

t = datetime . time (12 , 30)

print (d1 < d2)  True


delta = d2 - d1
print ( delta . days)  93

17
2) Modules:

os (path / dir ) : os.listdir(‘dir_path’)

csv

sqlite3

xmlrpc

18
‫الجمهورية العربية السورية‬
‫المعهد العالي للعلوم التطبيقية والتكنولوجيا‬

‫‪3- Numpy Module‬‬

‫‪19‬‬
3) Numpy:
np_arr = np.array([1,2,3,4])
NumPy is a Python library.
print(np_arr)  [1 2 3 4]
print(type(np_arr))  <class 'numpy.ndarray'>
NumPy is short for "Numerical Python".
print(np_arr.dtype)  int32
NumPy is used for working with arrays.
np_arr = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]],int)
terminal  pip3 install numpy
print(np_arr)
import numpy as np
[[ 1 2 3 4]
[ 5 6 7 8]
print(np.zeros(5))
[ 9 10 11 12]]
[0. 0. 0. 0. 0.]
print(type(np_arr))  <class 'numpy.ndarray'>
print(np_arr.dtype)  int32
print(np.ones(9))
[1. 1. 1. 1. 1. 1. 1. 1. 1.]
np_arr = np.array([1,"2",3.3,4])
print(np_arr)  ['1' '2' '3.3' '4']
ones = np.ones(9)
print(type(np_arr))  <class 'numpy.ndarray'>
print(np.mean(ones))
print(np_arr.dtype)  <U32
1.0

20
Exercises:

Exercises: recursive functions / factorial


inverting indexing of words in textual files
(os.curdir / )

21

You might also like