Topic B Classes and Objects v1-9!3!2022
Topic B Classes and Objects v1-9!3!2022
9. Two different ways to call Methods in object 12. Accessing private variables using getter/setter
+b= 6
+h=5 6.5
attributes ,
properties or
data members
Fields
• Fields can be declared directly inside class (as
point_class.py shown here)
or in constructors (more common)
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
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
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
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
s self.x = x
self.y = y
...
def __init__(self,others):
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
# 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 __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
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
9. Two different ways to call Methods in object 12. 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
Write OOP
- name : string (private)
- course: [ ] string (private)
Python code
+ phone : int (public)
…
Python code
- acc_no : int (private)
# name : string (protect)
- total : float (private)
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
Sav_Account
+ acno : int (public)
+ name : string (public)
+ money : float (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
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()
Exception
Handling
• raise ExceptionType("message")
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
m2
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
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
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.
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