0% found this document useful (0 votes)
7 views

Topic B Classes and Objects v1-9!3!2022

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Topic B Classes and Objects v1-9!3!2022

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 97

‫‪Topic B : CS210 OOP-Python‬‬

‫‪Classes and Objects‬‬


‫)‪(Part 1‬‬

‫‪Topic B: CS210 OOP-Python‬‬


‫‪Instructor: Dr. Ra’ed M. Al-Khatib‬‬
‫مدرس المساق د‪ .‬رعد الخطيب‬
‫من قسم علوم الحاسوب‬
‫بداية محاضرة اليوم‬ ‫تكنولوجيا المعلومات وعلوم الحاسوب – جامعة اليرموك‬
‫‪1‬‬ ‫كلية‬
Topic B :
CS 210 Object Oriented Programming
Spring 2020-2021
1. Defining a Class Classes and Objects
2. Make and add fields: attributes , properties or data members
3. from Module import *
4. add new fields anytime to the object
5. add Methods to the object
6. "Implicit" Parameter (self)
7. Object Methods (self , other) parameters
8. Constructors or initializer for Class
9. Two different ways to call Methods in object
10. toString or __str__ in object
11. Access Specifiers (Encapsulation):
 Public , Private, Protected
12. Accessing private variables using getter/setter
13. Exception Handling
CS 210 Object Oriented Programming
Topic B :
Spring 2020-2021
Topic B :
1. Defining a Class Classes and Objects
2. Make and add fields: attributes , properties or data members
3. from Module import * 1. Defining a Class

2. Make and add fields: attributes , properties or data members


4. add new fields anytime to the object 3. from Module import *

4. add new fields anytime to the object


5. add Methods to the object 5. add Methods to the object

6. "Implicit" Parameter (self)


6. "Implicit" Parameter (self) 7. Object Methods (self , other) parameters

8. Constructors or initializer for Class


7. Object Methods (self , other) parameters 9. Two different ways to call Methods in object

8. Constructors or initializer for Class


10. toString or __str__ in object
11. Access Specifiers (Encapsulation):
 Public , Private, Protected

9. Two different ways to call Methods in object 12. Accessing private variables using getter/setter

13. Exception Handling

10. toString or __str__ in object


11. Access Specifiers (Encapsulation):
 Public , Private, Protected
12. Accessing private variables using getter/setter
13. Exception Handling
Classes and Objects
Topic B • In this topic you will learn:
• Express classes and objects in Python
outlines • Implement methods and add data members
to classes
• Define access specifiers of data members
• Object-oriented programming (OOP)
involves programming using objects.
• An object represents an entity in
Overview the real world that can be distinctly
identified.
• For example, a student, a desk, a
clas
s na
General circle, a button, and point can all
class
identi me  be viewed as objects.
ty
Point • An object has a:
properties +x : int (float) public 1) a unique identity,
State
Data members
-y : int (float) Private(hid) 2) state,
3) and behaviors.
operations • The state of an object consists of
+ show(out): void
behavior a set of data fields (also known
methods as properties) with their current
L diagram values.
Class UM
• The behavior of an object is
defined by a set of methods.
• Object-oriented programming (OOP)
involves programming using objects.
• An object represents an entity in
Overview the real world that can be distinctly
identified.
• For example, a student, a desk, a
clas
s na
General circle, a button, and point can all
class
identi me  be viewed as objects.
ty
Rectangle • An object has a:
properties +length : int (float) public 1) a unique identity,
State
Data members
+width : int (float) public 2) state,
3) and behaviors.
operations • The state of an object consists of
+ area( ): float
behavior a set of data fields (also known
methods as properties) with their current
L diagram values.
Class UM
• The behavior of an object is
defined by a set of methods.
clas General
iagram
sn ss U ML d • Object-oriented programming (OOP)
identi ame  class Cla
ty involves programming using objects.
Circle
• An object represents an entity in
properties
State
+pi: float public the real world that can be distinctly
+radius: int (float) public
Data members identified.
operations
• For example, a student, a desk, a
+ area( ): float circle, a button, and point can all
behavior
be viewed as objects.
methods
• An object has a:
clas General
s na class 1) a unique identity,
identi me 
ty 2) state,
Circle 3) and behaviors.
properties +pi: int public • The state of an object consists of
State
Data members
+radius: int (float) public a set of data fields (also known
as properties) with their current
operations
+ area : float
values.
behavior • The behavior of an object is
methods defined by a set of methods.
L diagram
Class UM
L diagram • Object-oriented programming (OOP)
Class UM
involves programming using objects.
Circle
• An object represents an entity in
+pi: float public the real world that can be distinctly
+radius: int (float) public
identified.
• For example, a student, a desk, a
+ area( out ): float circle, a button, and point can all
be viewed as objects.
• An object has a:
c t U ML diagram
Obje 1) a unique identity,
2) state,
Circle
3) and behaviors.
+ pi = 3.14
+ radius = 5
• The state of an object consists of
+ color = 'Red' a set of data fields (also known
as properties) with their current
+ area(out) : float values.
• The behavior of an object is
defined by a set of methods.
L diagram
Class UM
Tringle

+b: float public L diagram


+h: int (float) public Class UM
t1
+ __init__( b , h ): void
+ area( out ): float
+b= 4
+ show( out ): string
+h=5

+ __init__( b=4 , h=5 ): void


L diagram
Class UM + area( out ): float
+ show( out ): string
t2

+b= 6
+h=5 6.5

+ __init__( b=6 , h=5 ): void


+ area( out ): float
+ show( out ): string
L diagram • Object-oriented programming (OOP)
Class UM
involves programming using objects.
Triangle
• An object represents an entity in
+ base: float public the real world that can be distinctly
+ height: int (float) public
identified.
• For example, a student, a desk, a
+ area( out ): float circle, a button, and point can all
be viewed as objects.
• An object has a:
c t U ML diagram
Obje 1) a unique identity,
2) state,
Circle
3) and behaviors.
+ pi = 3.14
+ radius = 5
• The state of an object consists of
+ color = 'Red' a set of data fields (also known
as properties) with their current
+ area(out) : float values.
• The behavior of an object is
defined by a set of methods.
Objects class Point:
x=0
__y = 0
clas General def show(self):
s na class
identi me  print("(", self.x , "," , self.__y , ")")
ty
Point #main code
p1 = Point()
+x : int (float) public p1.x =3 diagra m
properties
state -y : int (float) Private(hid) Object U ML
p1.__y =4
L diagram
p1.show() Object UM
operations
+ show(out): void
behavior Obje General
ct na class
identi me 
ass U ML diagram ty
Cl
An object has: P1
1) a unique identity,
2) state, properties +x = 3
state -y = 4
3) and behaviors.
An object has both a state and behavior. operations
The state defines the object, + show(out): void
and the behavior defines what the object behavior
does.
• An object has both a
state and behavior.
• The state defines
the object,
Objects • The behavior
defines what the
object does.
• Python was built as a

Defining procedural language


• OOP exists and
works fine, but Java
a Class probably does
classes better than
Python
• Declaring a class in
class Point: Python:
x = 0
y = 0 class name:
#main code statements
class Point:
x=0
y=0
UML vs. def translate(self, a , b):
self.x = self.x + a
Python self.y += b

Class Name: Point A class template #------ ------


Data Fields: # main code
x _______ Point Object 1 Two objects of p1 = Point()
y _______ the Point class
Data Fields:
print("p1 ==> x= "+ str(p1.x))
x is 2 print("p1 ==> y= "+ str(p1.y))
Methods: y is 5
translate
p1.translate(2 , 5)
Point Object 2
print("p1 ==> x= "+ str(p1.x))
Data Fields: print("p1 ==> y= "+ str(p1.y))
x is 10
y is 12
declare or add
fields:
which are the

attributes ,
properties or
data members
Fields
• Fields can be declared directly inside class (as
point_class.py shown here)
or in constructors (more common)

•Python does not really have encapsulation or


1 class Point: private fields
2 x = 0 •relies on caller to "be nice" and not mess with
objects' contents
3 y = 0 • name = value
•Example:

class Point:
x=0
y=0

# main program
p1 = Point()
p1.x = 2
p1.y = -5
Using a Class
point_class.py
import point_class
or from point_class import * point_class.py
– client programs must import the classes they use
1 class Point:
2 x = 0
point_main.py 3 y = 0

1 from point_class import *


2 # import point_class
3
4 # main
5 p1 = Point()
6 p1.x = 7
7 p1.y = -3
8 ...
9 print(p1.x)
10 p2 = Point()
print(p2.y) #  0
11 print(p1.y) #  -3
12
Dynamic new
Attribute for Object
in Python • you can add fields
anytime to the object
gra m
dia
Using a Class Cla ss Point
x = int
y = int

import class + GetX( … ): void


point_class.py + setX( … ): void
client programs must import + GetY( … ): void
+ setY( … ): void
the classes they use
1 class Point:
2 x = 0
point_main.py 3 y = 0
am
d ia gr
t
bjec
1 from point_class import * O p1
2 # or import point_class
3 # main x=7
4 p1 = Point() y = -3
5 p1.x = 7
6 p1.y = -3
7 print(p1.x) g r am
8
#================= ct dia
p2 = Point() je
9 print(p2.y) #  0 Ob p2
10 print(p1.y) #  -3
11 # Python objects are dynamic x=0
12 (can add fields any time!)
13 p2.name = "point 2" y = -3
name = "point 2"
add
Methods
to
the object
Object
Methods • Use the following to define a method
for a class
def name(self, parameter, ..., parameter):
class Point: statements

x=0
• self must be the first parameter to any
y=0
object method
def translate(self, dx, dy): • self represents the "implicit
self.x += dx parameter"
self.y += dy
# --- main code • Self is used to access the object's fields
through
p1 = Point()
p1.translate(4 , 3)
print(p1.x)
print(p1.y)
Using a Class
point_class.py
import point_class
or from point_class import * point_class.py
– client programs must import the classes they use
1 class Point:
2 x = 0
point_main.py 3 y = 0

1 from point_class import *


2 # import point_class
3
4 # main
5 p1 = Point()
6 p1.x = 7
7 p1.y = -3
8 ...
9 print(p1.x)
10 p2 = Point()
print(p2.y) #  0
11 print(p1.y) #  -3
12
• Python: self, explicit
def translate(self, dx, dy):
self.x += dx
self.y += dy

•Exercise for the point class:


 Write set_location, and
distance_from_origin methods
 then, distance_btwn2points
method.
Exercise Answer
Exercise:
Write set_location, and distance_from_origin methods.
from math import *
class Point:
x=0
y=0

def set_location(self, x, y):


self.x = x
self.y = y

def distance_from_origin(self):
return sqrt(self.x * self.x + self.y * self.y)

# main code
p1 = Point()
p1.set_location(4, 3)
print( p1.distance_from_origin() )
Again, def name(self, other):

Object statements
• self must be the first

Methods parameter to any object


method
• must access the object's

self , other fields through the self


reference
• When you understand what
parameters self is used to, then you are in
middle of the journey
Exercise: Write set_location, and distance_from_origin methods
then, distance_btwn2points methods.

from math import *


class Point:
x=0
y=0
def set_location(self, x, y): …
self.x = x ….
self.y = y # main code
p1 = Point()
def distance_from_origin(self):
return sqrt(self.x * self.x + self.y * self.y) p1.set_location(4, 3)
print(p1.distance_from_origin())
def distance_btwn2points(self, other):
dx = self.x - other.x
dy = self.y - other.y p2 = Point()
return sqrt(dx * dx + dy * dy) p2.set_location(4, 5)
# main code print(p1.distance_btwn2points(p2))

Constructo
rs or
initializer
for Class
• A Python class uses variables to store data
fields and defines methods to perform
actions.

Classes: • Additionally, a class provides a special


type method, known as initializer, which

Constructors
is invoked to create a new object.
• An initializer can perform any action, but
initializer is designed to perform
initializing actions, such as creating the
data fields of objects.

class ClassName:
initializer
methods
def __init__(self, parameter, ...,
parameter):
statements

•A constructor is a special method with the name


__init__
Classes: •Example:

Constructor class Point:


def __init__(self, x, y):

s self.x = x
self.y = y
...

•How would we make it possible to construct a


Point() with no parameters to get (0, 0)?
Constructing Objects
Once a class is defined, you can create objects from the class by using the
following syntax, called a constructor: initializer

def __init__(self,others):

1. It creates an object in the memory for object


the class. Data Fields:

2. It invokes the class’s __init__ method


to initialize the object. The self
parameter in the __init__ method is
__init__(self, …)
automatically set to reference the
object that was just created.
Constructors
– Full Example:
class Point:
class Point: x=0
def __init__(self, x, y): y=0
self.x = x
self.y = y def translate(self, dx, dy):
self.x += dx
def translate(self, dx, dy): self.y += dy
self.x += dx
self.y += dy # main code
ed p1 = Point( )
# main code Can be shorten
p1.x = 3
p1 = Point(3, -4) and replaced to
be p1.y = -4
print(p1.x) print(p1.x)
print(p1.y)
Constructors
– Full Example:
class Point:
class Point: x=0
def __init__(self, x, y): y=0
self.x = x
self.y = y def translate(self, dx, dy):
self.x += dx
def translate(self, dx, dy): self.y += dy
self.x += dx
self.y += dy # main code
ed p1 = Point( )
# main code Can be shorten
p1.x = 3
p1 = Point(3, -4) and replaced to
be p2.x = -4
print(p1.x) print(p1.x)
Constructing Objects
The effect of constructing a point object using Point(5,7) is shown below:

1. Creates a Point object. Point object

2. Invokes __init__(self, x, y) Point object


x: 5
y: 7

38
Two
different
ways to call
Methods
in object
Calling Methods
• A client can call the methods of an object in
two ways:
– (the value of self can be an implicit or
class Point:
explicit parameter) def __init__(self, x, y):
self.x = x
1) object.method(parameters) self.y = y

or def translate(self, dx, dy):


2) Class.method(object, self.x += dx
parameters) self.y += dy

# main code
p1 = Point(3, -4)
print(p1.x)
• Example:
p1.translate(1, 5)
p1 = Point(3, -4) # create object
# or
p1.translate(1, 5) Point.translate(p1, 1, 5)
Point.translate(p1, 1, 5)
gra m
s dia
s
''' Cla
std_list_courseMarks_06102019.py

'''
class Student:
#main program
def __init__(self, id , n, c , m): s1= Student(201990887766, 'Sami' , ['cs210' , 'cs130' ,
self.id = id 'math102'], [90, 90, 20])
self.name = n
self.courses =c
self.marks =m s1.printAll()

def printAll(self): s1.courses.append('bio222')


print("id= ", self.id, "name= ",self.name, "\n courses= "\ s1.marks.append( 80)
,self.courses , "\n marks= ",self.marks )
print('-----after append -----')
def avg(self): s1.printAll()
sum = 0.0
c=0 print('\n-----print SUM & avg -----')
for m in self.marks: s1.avg()
c+=1
sum += m
print("sum = ", sum, " c= " , c)
print("avg= " , sum/c)
Full example
to Review :
Constructor __init__
self , other
Write a Equation Class Declare a constructor for the ( a, b & c ) of the
Equation . Then , add a method called { sum(self, other) } to add two 2
Eq.s as objects {e3 = e1+e2 } from the Equation Class . After that, write a
display(self) method for each Equation object that print out the final output
like " 2x^2 + 4x -5 ", using if elif decision and conditions. final output
must be 
draw UML class diagram for Equation Class
and draw UML object diagram for e1, e2 & e3
general ax2 + bx + c = 0
Equation

Write a Equation Class :


1- Declare a constructor for the ( a, b & c ) of the Equation .

2- Add a method called { sum(self, other) } to add two 2 Eq.s as


objects {e3 = e1+e2 } from the Equation Class .
3- Write a display(self) method for each Equation object that
print out the final output like " 2x^2 + 4x -5 ", using if elif decision and
conditions

4- the final output must be 

5- draw UML class diagram for Equation Class


and draw UML object diagram for e1, e2 & e3
 e1+e2  sum(self, other)
e1 2x^2 + 4x -5
e2 -5x^2 -6x +8
-------------------------------
e3 -3x^2 -2x +3
Homework : using Equation class
1- to add 2Eq’s  e3 = e1 + e2
2- to sub 2Eq’s  e3 = e1 - e2
3- to mul 2Eq’s  e3 = e1 * e2
4- to div 2Eq’s  e3 = e1 / e2

Write a Equation Class :


1- Declare a constructor for the ( a, b & c ) of the Equation .

2- Add a method called { sum(self, other) } to add two 2 Eq.s as


objects {e3 = e1+e2 } from the Equation Class .
- Add a method called { sub(self, other) } to subtract two 2 Eq.s as
objects {e3 = e1 - e2 } from the Equation Class .
- Add a method called { mul(self, other) } to multiple two 2 Eq.s as
objects {e3 = e1 * e2 } from the Equation Class .
- Add a method called { div(self, other) } to divide two 2 Eq.s as
objects {e3 = e1 / e2 } from the Equation Class .

3- Write a display(self) method for each Equation object that print


out the final output like " 2x^2 + 4x -5 ", using if elif decision and
conditions
toString
or
__str__
in object
toString or __str__ in object
class Point:
def __init__(self, x, y): returns strings
self.x = x
self.y = y
like "( 3, -4 )"
or "( x=3, y=-4 )"
# main code
p1 = Point(3, -4)
print(p1.x)

What is the problem


print( p1.x + " , " + p1.y )
print( "x= " + p1.x + " , " + "y= " + p1.y )

print( str(p1.x) + " , " + str(p1.y) )


print( "x= " + str(p1.x) + " , " + "y= " + str(p1.y) )
def __str__(self):
return string
toString and
– equivalent to Java's toString (converts object
__str__ to a string)
– invoked automatically when str or print is
called

Exercise: Write a __str__ method for Point


objects that returns strings like "(3, -14)"

def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"

def display(self):
print(str(self))
Complete Point Class
point.py Write a __str__ method for Point objects
that returns strings like "(3, -14)"
from math import *
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_from_origin(self):
return sqrt(self.x * self.x + self.y * self.y) # main code
def distance_btwn2points(self, other): p1 = Point(3, -14)
dx = self.x - other.x print(p1.x)
dy = self.y - other.y
return sqrt(dx * dx + dy * dy)
p1.display( )
def translate(self, dx, dy): # or
self.x += dx
self.y += dy Point.display(p1)
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
def display(self):
print(str(self))
class Quiz:
def __init__(self,x=0,y=1,z=2): print(Q2.__sum(Q1)) # error private method
self.q1=x
self._q2=y
self.__q3=z To call the function __eq__ of line 29, you will write in main:
def __iadd__(self,w): print(Q1==Q2) ‫قاسم العمري‬
self.q1+=w a. print(Q1==Q2)
self._q2-=w b. print(Q1.__q3==Q2.__q3)
self.__q3*=w c. print(==(Q1))
return self d. print(Q1.__eq__(Quiz))
def __add__(self,w):
Q=Quiz() If Q1 and Q2 are objects of type class Quiz. Suppose that
Q.q1+=w.q1 operator *= is overloaded. Then the statement: Sally
Q._q2+=w._q2 Q1*=Q2
Q.__q3+=w.__q3 Is equivalent to:
return Q a. Quiz.__imul__(Q1,Q2) # main code
def __sum(self,other): b. Q1=Q1*Q2 Q1=Quiz()
self._q2=self.q1+other.__q3 c. Q2.__imul__(Q1) Q2=Quiz(10,10)
return self d. Q1.__mul__(Q2) print(~Q1)
def __isub__(self,w):
‫فرح‬
self.q1=w._q2
Q2+=5 Q3 = ~Q1
return self
print(Q2) Q3.__str__( )
def __invert__(self):
if self.q1<self._q2:
Complete Circle Class

Write a Circle Class :


1- Pi = 22.0/7.0 is a public data member.
2- Declare a constructor for the radius of the Circle.
3- Add a method called ( Area ) to calc. the area of the circle.
R ad
4- Write a __str__ method for Circle objects that returns strings like i us
"[Radius = 3.5, The circle Area = 38.0]"
5- Write a display method to print the final str returned output.
6- In the main code to make c1 as new object with radius=3.5 . And print the final
output.
7- In the main code to make c2 as new object with radius=7.0 . And print the final
output.
8- Draw the UML Class Diagram for Circle Class.
9- Draw the Object Diagram for c1, c2 object.
10- give the code to change the radius attr. for c2 to be = 8.5 and print
the final output.
11- Name the program as circle.py
UML Circle Class

Circle
+ pi : float (public)
+ Raduis : float (public)
+ __init__( in r ): void
+ Area(in r:float ): float
+ __str__( … ): String
+ display( … ): void

Complete
Circle Class
Write a Python oop code to define a Rectangle Class Name your programHomework:a
(rectangle04_11_2021.py ) as follows :
1- Declare a constructor __init__ for the length (L) & width (w) of the Rectangle,
which are the main attributes .
2- Add a method called ( area ) to calc. the area of Rectangle .
3- Add a method called ( display ) to print out the output “L = , w = , area = ”.
4- in the main code create r1 as first object with L=3 & w=4 . And print the final output
using r1.display( ).
5- in the main code create r2 as new object with L=9 & w=6 . And print the final output
using r2. display( ).
6- Draw the UML Class Diagram for Rectangle Class. e cta n gle
R
7- Draw the Object UML Diagram for r1, r2 objects.
8- In main code, change the length attr. for r2 to be = 7.5 and print the final output.
9-Write a __str__ method for Rectangle objects that returns strings like
"[length= 3 & width= 4 , The Rectangle Area = 12]“
10- Add a method called ( sum2Rec(self , other)) to add r1, r2.and call it
from main code ( r1 =sum2Rec(r2) )
Write a Python oop code to define a Rectangle Class as follows : Homework:a
1- Declare a constructor __init__ for the length (L) & width (w) of
the Rectangle, which are the main attributes .
2- Add a method called ( Area ) to calc. the area of the Rectangle .
3- Write a __str__ method for Rectangle objects that returns strings like gle
R e cta n
"[length= 3 & width= 4 , The Rectangle Area = 12]“

5- Write a show method to print the final str toString returned output.
6- r1 as first object with L=3 & w=4 . And print the final output
in main code to create
using r1.show( ).
7- in main code to create r2 as new object with L=9 & w=6 . And print the final outputusing
r1.show( ).
(‫باإلمكان رسمها بخط اليد‬
8- Draw the UML Class Diagram for Rectangle Class.
‫على ورقة ورفع صورة‬
9- Draw the Object UML Diagram for r1, r2 objects. ‫)الورقة مرفقه‬

10- In main code, change the length attr. for r2 to be = 6.5 and print the
final output.
11-Name your program ( Rectanlge.py )
Write a Python oop code to define a Triangle Class as follows : Homework:a
1- Declare a constructor __init__ for the base(b) & height(h) of the
Triangle , which are the main attributes .
2- Add a method called ( area ) to calc. the area of the Triangle .
3- Write a __str__ method for Triangle objects that returns strings like
"[base= 4 & height= 5 , The Triangle Area = 10]“
5- t1 as first object with b=4 & h=5 . And print the final output using
in main code to create
print( t1 ).
7- in main code to create t2 as new object with b=6 & h=5 . And print the final output using
print( t2 ).
8- Draw the UML Class Diagram for Triangle Class. Triangle
9- Draw the Object UML Diagram for t1, t2 objects.
10- In main code, change the height attr. for t2 to be = 6.5 and print the
final output.
11-Name your program (Triangle.py )
CS 210 Object Oriented Programming
Topic B :
Spring 2020-2021
Topic B :
1. Defining a Class Classes and Objects
2. Make and add fields: attributes , properties or data members
3. from Module import * 1. Defining a Class

2. Make and add fields: attributes , properties or data members


4. add new fields anytime to the object 3. from Module import *

4. add new fields anytime to the object


5. add Methods to the object 5. add Methods to the object

6. "Implicit" Parameter (self)


6. "Implicit" Parameter (self) 7. Object Methods (self , other) parameters

8. Constructors or initializer for Class


7. Object Methods (self , other) parameters 9. Two different ways to call Methods in object

8. Constructors or initializer for Class


10. toString or __str__ in object
11. Access Specifiers (Encapsulation):
 Public , Private, Protected

9. Two different ways to call Methods in object 12. Accessing private variables using getter/setter

13. Exception Handling

10. toString or __str__ in object


11. Access Specifiers (Encapsulation):
 Public , Private, Protected
12. Accessing private variables using getter/setter
13. Exception Handling
Encapsulation

Access Specifiers in Python •Public


•Private
•Protected
class A:
Encapsulation def __init__(self):
by self.__priv = "I am private"
self._prot = "I am protected"
self.pub = "I am public"
Accessing private variables using getter/setter

class A:
def __init__(self): class Point:
def __init__(self, x, y):
self.__priv = "I am private"
self.__x = x
self._prot = "I am protected"
self.__y = y
self.pub = "I am public"
def SetX(self, x):
Point self.__x = x
def GetX(self):
- x : int (private) return self.__x
+ y : int (private)
def SetY(self, y):
+ SetX(in x:int ): void self.__y = y
+ GetX(out x ): int def GetY(self):
return self.__y
+ SetY(in y:int ): void
+ GetY(out y ): int
p1 = Point(3, 5) # main code
print(p1.__x) p1 = Point(3, 5)
privat print(p1.GetX( ))
e
What is the class UML diagram from the following code?

Point Point
- x : int (private) - x : int (private)
+ y : int (private) + y : int (public) class Point:
def __init__(self, x, y):
+ SetX(in x:int ): void + SetX(in x:int ): void self.__x = x
+ GetX(out x ): int + GetX(out x ): int self. y = y

- SetY(in y:int ): void - SetY(in y:int ): void def SetX(self, x):


+ GetY(out y ): int + GetY(out y ): int self.__x = x
def GetX(self):
return self.__x
Point Point def __SetY(self, y):
self.__y = y
+ x : int (private) - x : int (private)
def GetY(self):
- y : int (public) + y : int (public)
return self.__y
+ SetX(in x:int ): void + SetX(in x:int ): void
+ GetX(out x ): int + GetX(out x ): int
- SetY(in y:int ): void + SetY(in y:int ): void
+ GetY(out y ): int + GetY(out y ): int
Student
- id : int (private)

Write OOP
- name : string (private)
- course: [ ] string (private)

Python code
+ phone : int (public)

for the + __init__( in id, name , phone ): void


+ setid( in id:int ): int

following + getid(out y ): int


UML class + registerCrs( in crs:string ): string


+ display ( … ): void
diagram:
#Solution
class Student:
def __init__(self, i, n , t):
self.__id = i # private def __str__(self):
self.__name = n # private return " id= \t "+str(self.__id)\
self.phone = t # public + "\n name: \t " + str(self.__name)\
self.__course = [ ] # private and list + "\n courses: " + str(self.__course)\
def setid(self, i): + "\n phone: " + str(self.phone)
self.__id = i def display(self):
def getid(self): print(str(self))
return self.__id
# main code
def setname(self, n):
s1 = Student(111, 'Wael Jafaar', '0778899123' )
self.__name = n
s1.register('CS210 oop Py')
def getname(self):
s1.register('CS130 OS')
return self.__name
s1.register('CS210L oop Py')
def register(self, c): s1.register('CS130 OS') # error
if not (c in self.__course): s1.display()
self.__course.append(c)
elif (c in self.__course):
print(c + " <==This course is register before")
Write OOP Student
- id : int (private)
Python code # name : string (protect)
- courses : [ ] string (private)
for the - marks : [ ] int (private)
+ phone : int (public)
following + __init__( in id, name , phone ): void

UML class + setid( in id:int ): int


+ getid(out y ): int

diagram: + addCrs( in crs: string ): void

+ addMrks( in mrk: int ): void


+ display ( … ): void
Write OOP Bank

Python code
- acc_no : int (private)
# name : string (protect)
- total : float (private)

for the + phone : String (public)

following
+ __init__( in i , name , phone ): void
+ setid( in i : int ): int
+ getName (out name ): String

UML class
+ addsalary( in money: float ): void

+ __str__ ( … ): String

diagram:
+ display ( … ): void
UML class diagram UML object diagram UML object diagram

Bank b1 b2
- accNo : int (private) - accNo = 112233
- accNo = 442293
# name : string (protect) # name = 'Sami'
# name = ‘Fadi'
- money : float (private) - money : 1050 - money : 2250
- accType : String (private) - accType : 'Saving account'
- accType : 'Saving account'
+ phone : String (public) + phone : '07956765434'
+ phone : '07756765004'

+ __init__( in i , name , phone ): void + __init__( in i , name , phone ): void + __init__( in i , name , phone ): void
+ setid( in i : int ): void + setid( in i : int ): void
+ setid( in i : int ): void
+ getid (out accNo): int + getid (out accNo): int
+ getid (out accNo): int
+ addmoney ( in money: float ): void + addmoney ( in money=505.75): void + addmoney ( in money=105.00): void

+ __str__ ( … ): String + __str__ ( … ): String


+ __str__ ( … ): String
+ show ( … ): void + show ( … ): void
+ show ( … ): void
SavingAccount
+ accno : int (public) SavingAccount
+ name : string (public)
+ accno : int (public)
+ money : float (public)
+ name : string (public)

+ __init__( in acc , n ,m ): void + salary : int (public)

+ addmoney( in a:int , m1: float ): void


+ __init__( in acc , n ,m ): void
+ __str__ ( … ): String
+ addmoney( in a:int , m1: float ): void
+ show( … ): void
+ __str__ ( … ): String
+ show( … ): void

Sav_Account
+ acno : int (public)
+ name : string (public)
+ money : float (public)

+ __init__( in acc , n ,m ): void


+ __str__ ( … ): String
+ addmoney( in a:int , m1: float ): void
+ show( … ): void
Write OOP Bank

Python code - acc_no : int (private)


+ name : string (public)

for the - money : float (private)


+ phone : String (public)

following
UML class
+ __init__( in i , name , phone ): void
+ setid( in i : int ): int

diagram:
+ addmoney ( in money: float ): void

+ __str__ ( … ): String
+ display ( … ): void
Write OOP Bank

Python code - acc_no : int (private)


+ name : string (public)

for the - money : float (private)


+ phone : String (public)

following
UML class
+ __init__( in i , name , phone ): void
+ setid( in i : int ): int

diagram:
+ addmoney ( in money: float ): void

+ __str__ ( … ): String
+ display ( … ): void
# bank class on https://path2code.com/p2c/login.php
class Bank: Bank
def __init__(self, acc_no, name, money, phone): - acc_no : int (private)
self.__acc_no = acc_no + name : string (public)
self.name = name
# money : float (private)
self._money = money
+ phone : String (public)
self.phone = phone
self.id = 0
+ __init__( in i , name , phone ): void
def addmoney(self, acc_no, money):
if self.__acc_no == acc_no: + setid( in i : int ): int
self._money += money + addmoney ( in acc_no , money): void
else:
+ __str__ ( … ): String
print('not the same account number , please check again')
+ display ( … ): void
def setid(self, i):
self.id = i
return self.id
def __str__(self):
str1 = f'Account number: {self.__acc_no} for Name: {self.name}\n\n'
str2 = f'The total money = {self._money} Jordan Dinner'
return f'{str1}{str2}'
def display(self):
print(str(self))
bnk1 = Bank(200234, 'Sami', 1500.35, '077004532')
bnk1.addmoney(200234, 499.65)
bnk1.display()
class Bank:
def __init__(self, i, n, m): Bank
self.__acc_no = i
self.name = n
self._money = m - acc_no : int (private)
def addmoney(self, acc_no, money): + name : string (public)
if self.__acc_no == acc_no: # money : float (protect)
self._money += money
else:
print('not the same account number ') + __init__( in i,n,m ): void
def __str__(self):
+ addmoney ( in acc_no , money): void
str1 = 'Account: ' + str(self.__acc_no)
str2 = ' Total ='+ str(self._money )
+ __str__ ( … ): String
return str1 + str2

# main code
bnk1 = Bank(200234, 'Sami', 1500.35)
bnk1.addmoney(200234, 499.65)
print(bnk1)
bnk1 Bank
- acc_no : int (private)
- acc_no : int (private)
- name : string (private)
+ name : string (public)
# money : float (protect)
+ money : float (private)

+ __init__( in i , n , m , p ): void
+ __init__( in i , n , m , p ): void
+ addmoney ( in acc_no , money): void
+ addmoney ( in acc_no , money): void
+ __str__ ( … ): String
+ __str__ ( … ): String
•''' full example for private and protect attr.
•'''
class point3d:
def __init__(self, i, j, k):
self.x=i
self._y=j
self.__z=k

def printAll(self):
print("x= ", self.x, " y= ",self._y, " z= ",self.__z )

#main program
p1= point3d(1,2,3)
p1.printAll()
p1.x=5
p1.printAll()
p1._y=10 # protectec _y
p1.printAll()

p1.__z=29 # new __z attribute without touch private self.__z


print('\n\t p1.__z= ', p1.__z)
p1.printAll()
raise

Exception
Handling
• raise ExceptionType("message")

• useful when the client uses your object improperly


• types: ArithmeticError, AssertionError, IndexError,
NameError, SyntaxError, TypeError, ValueError
• Example:

class BankAccount:
Generating
...
def deposit(self, amount):
Exceptions
if amount < 0: def register(self, c):
raise ValueError("negative amount")
...
if not (c in self.__course):
self.__course.append(c)
if (c in self.__course):
raise ValueError("this course is registered before")

# main code
s1 = Student(111, 'Wael Jafaar', '0778899123' )
s1.register('CS210 oop Py')
s1.register('CS130 OS')
s1.register('CS130 OS')
s1.display()
try:

except
Clause
Revision
try: …. except … as e:
class Division:
def __init__(self,x,y):
self.x=x #main code
self.y=y
try: d1= Division(-8,4)
self.z = self.x/self.y d1.show()
print("pass ==> z=" + str(self.z)) print("d1.z= ",d1.z)
except ZeroDivisionError as e:
print('-----------')
print('Error handling of type: ', type(e)) d2= Division(25,0)
self.y=1 d2.show()
self.z = self.x/self.y
d2.show() print("d2.z= ", d2.z)
print("new updated z=" + str(self.z))

def __str__(self):
return "Divide: " + str(self.x) + "/" + str(self.y) + " ==> z=" + str(self.z)
def show(self):
print(str(self))
try: …. except … as e: https://youtu.be/iUToXeE5QYM

class Square_root:
def __init__(self , x):
self.x = x
try :
if(self.x < 0 ):
raise ValueError
else:
print(x**0.5)
except ValueError as e:
print("That is a negative number!")
print(str((-1*x)**0.5) + 'i')

# main code
number=int(input("Enter a value of number="))
sqrt1 = Square_root(number)
Procedural vs. Object-Oriented
To explore the differences between the procedural paradigm and the
object-oriented paradigm.
1. The object-oriented programming approach organizes
programs in a way that mirrors the real world, in
which all objects are associated with both attributes
and activities.
2. Using objects improves software reusability and
makes programs easier to develop and easier to
maintain.
3. Programming in Python involves thinking in terms of
objects; a Python program can be viewed as a
collection of cooperating objects.
Extra Examples
for Ch-2
# point_dynamic_extra_26092019

'''
class Point: # 1- static integer
x=0
y=0
'''
'''
class Point: # declare data members , then define Constructor __init__
x=0
y=0

def __init__(self, i=9, j=9 , k=9 ):


self.x = i
self.y = j #main code
self.z = k
''' p1 = Point( 6, 77, 'Hadi Kadi')
class Point: # declare data members , then define Constructor __init__
x=0 p1.x = 677
y=0
print(p1.x)
def __init__(self, i, j , k ): print("p1.z ==>", end='' )
self.x = i print( p1.z)
self.y = j
self.z = k p1.z = 7654
''' print("p1.z ==>", end='' )
class Point: # in Python No need to declare members (attr.s) print(p1.z)
def __init__(self, i, j ): # dynamic ==> Constructor __init__
self.x = i p1.section = 'Sec 7'
self.y = j print("p1.section ==>", end='' )
''' print(p1.section)
Exercises
Mobile m1

+Serial: int (public) +Serial= 1234 (public)


- brand: string (private) - brand= 'iPhone' (private)
#Model: string (protect) #Model= 'S21' (protect)

__init__(in s, i, m): void __init__(in ……): void


+setmodel (in s:int):void +setmodel (in ….):void
+getbrnd(out brand): string +getbrnd(out brand): string
+ display(out All): void + display(out All): void

m2

+Serial= 455 (public)


- brand= ‘Samsung' (private)
#Model= ‘Note10' (protect)

__init__(in ……): void


+setmodel (in ….):void
+getbrnd(out brand): string
+ display(out All): void
• Exercise: Write a Mobile class. Eagle

- type: string (private)


# name: string (protect)
Bird - count: int (private)

+ type: string (public)


# name: string (protect) __init__(in t, n, c ): void
- count: int (private)

class Eagle:
__init__(in t, n, c ): void def __init__(self, t , n='' , c = 51 ):
self.__type = t
self._name = #n
self.__count = c
class Bird:
def __init__(self, t , n=' ' , c = 21 ): def display(self):
self.type = t print(self.__type, self._name,
self._name = n self.__count)
self.__count = c
b1 = Eagle( 'Hoopoe', 'crown' )

b1.display( )
What is the correct class UML diagram?

 Eagle Eagle

- type: string - type: string Eagle


# name: string # name: string
+ count: int - count: int
- price: float - price: int + type: string
# name: string
- count: int
__init__(in t, n, c , p ): void __init__(in t, n, c , p): void - price: int
setPrice(in m): void setPrice(in m): void
show( ): output show( ): output
__init__(in t, n, c, p ): void
setPrice(in m): void
 Eagle show( ): output
class Eagle:
Eagle
def __init__(self, t , n=' ' , c = 51 , p
self.__type = t
- type: string self._name = n
# name: string
self.count = c
- count: int
- price: float self.__price = p

def show(self):
__init__(in t, n, c , p ): void
Write an OOP Pyhton code to create class called
( Fraction ) with two attributes : x as hidden and
private attribute, y as public attribute?
div = x/y
1- make a constructor ( __init__ ) to create this class
( Fraction ) ?
2- make a method calcDivide to compute result of
self.div = x/y*-1

3- add an exception to calcDivide if y = 0 , there is


Error Division by Zero? to correct make y =1 and
complete the calcuations
4- create two objects from Fraction class and print
them using __str__ and show() methods:
5- make a Sum (self,other) to add two fraction
objects f3=f1.sum(f2) and the result of summation
in obj. f3?
class Fraction:
def __init__(self,i,j):
self.__x= i
self.y= j
try:
print("x divide by y ==>", self.__x , "/" , self.y ,"=",self.__x/self.y)
self.__x/self.y
except ZeroDivisionError:
self.y=1
print("Error Division by Zero, bcze self.y= 0")

def Sum (self,other) :


f3=Fraction(0,0)
if self.y!= other.y:
self.y=self.y*other.y
self.__x=self.__x*other.y
other.__x=other.__x*self.y
elif self.y<0:
self.__x=self.__x*-1
self.y=self.y*-1
elif other.y>0:
other.__x=other.__x*-1
other.y=other.y*-1
f3.__x=self.__x + other.__x
f3.y= self.y
return f3
def __str__ (self):
return ("Fraction ==>" + str(self.__x) + "/" + str(self.y) +"=" +str(self.__x/self.y))
def show (self):
print (str(self))
Advanced questions
Exercise
• Exercise: Write a Fraction class to represent
rational numbers like 1/2 and -3/8.

• Fractions should always be stored in reduced form; for


example, store 4/12 as 1/3 and 6/-9 as -2/3.
– Hint: A GCD (greatest common divisor) function may help.

• Define add and multiply methods that accept another


Fraction as a parameter and modify the existing
Fraction by adding/multiplying it by that parameter.
https://gist.github.com/mustaa/2350807

https://runestone.academy/runestone/books/published/pythonds/Introduction/ObjectOrientedProgra
mminginPythonDefiningClasses.html

https://www.tutorialspoint.com/fraction-module-in-python
Exercise
• Exercise: Write a Fraction class to represent rational numbers like 1/2 and -3/8.

• Fractions should always be stored in reduced form; for example, store 4/12 as 1/3 and
6/-9 as -2/3.
– Hint: A GCD (greatest common divisor) function may help.

• Define add and multiply methods that accept


another Fraction as a parameter and modify the
existing Fraction by adding/multiplying it by that
parameter.
Summary
Q#1:
• For the following diagram, describe the meaning of the relationship?
Q2
• Draw a UML class for class Ellipse
Q3
• Draw the relation between the following two classes:
• Professor 'has a' class to teach
Q4

a- What is the type of relationship between class line and class geometrical object?

b- What is the type of relationship between class Sheet and class Drawing objects?
Q5

c- Mention two operations (methods) for class Text?

d- Mention two data members (attributes) for class Document?


Q6

e- How many composition relationships are in this diagram?

f- How many Aggregation relationships are in this diagram?


Class
Diagrams
Example

You might also like