Professional Documents
Culture Documents
Chapter 10
Chapter 10
Python Implementation of OO
Programming
Declaration
These slides are made for UIT, BU students only. I am not
holding any copy write of it as I had collected these study
materials from different books and websites etc. I have not
mentioned those to avoid complexity.
Output:
<class '__main__.MyClass'>
Code:
p1 = MyClass()
print(p1.x)
Output:
5
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Output:
John
36
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Output:
Hello my name is John
11/17/2023 11:47 PM Dr. Dipankar Dutta, UIT, BU 1.15
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:
Example
Code:
Use the words mysillyobject and abc instead of self:
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()
11/17/2023 11:47 PM Dr. Dipankar Dutta, UIT, BU 1.16
Class and Instance Variables
Instance variables are for data, unique to each instance and
Class variables are for attributes and methods shared by all
instances of the class.
Instance variables are variables whose value is assigned inside
a constructor or method with self
Whereas class variables are variables whose value is assigned
in the class.
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
# Constructor
def __init__(self):
self.value = "Inside Parent"
# Constructor
def __init__(self):
self.value = "Inside Child"
obj1.show()
obj2.show()
Output:
Inside Parent
Inside Child
obj.show()
obj.display()
Output:
Inside Child
Inside Parent2
class Parent():
Output:
Inside GrandChild
Inside Parent
def show(self):
print("Inside Parent")
def show(self):
# Driver's code
obj = Child()
obj.show()
class Parent():
def show(self):
print("Inside Parent")
def show(self):
# Driver's code
obj = Child()
obj.show()
def my_function():
print("Hello from a function")
my_function()
my_function(“RAM")
my_function(“SAM")
my_function(“JODU")
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
def my_function(food):
for x in food:
print(x)
my_function(fruits)
print(my_function(3))
print(my_function(5))
print(my_function(9))
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print(shout('Hello'))
yell = shout
print(yell('Hello'))
def create_adder(x):
def adder(y):
return x+y
return adder
add_15 = create_adder(15)
print(add_15(10))
def hello_decorator(func):
def inner1(*args, **kwargs):
print("before Execution")
# getting the returned value
returned_value = func(*args, **kwargs)
print("after Execution")
# returning the value to the original frame
return returned_value
return inner1
def decor(func):
def inner():
x = func()
return 2 * x
return inner
print(num())
Output:
400
Output:
TIU
Good for performing short Good for any cases that require
operations/data manipulations. multiple lines of code.
print(Max(1, 2))
Output:
2
Output:
[5, 7, 97, 77, 23, 73, 61]
Output:
193
# initializing list
lis = [1, 3, 5, 6, 2, ]
def Print(self):
print("Emp class called")
class Person(object):
# Constructor
def __init__(self, name):
self.name = name
Output:
UIT1 False
UIT2 True
# parent class
class Person(object):
def display(self):
print(self.name)
print(self.idnumber)
class B(A):
def __init__(self, roll):
self.roll = roll
object = B(23)
print(object.name)
11/17/2023 11:47 PM Dr. Dipankar Dutta, UIT, BU 1.100
Inheritance
Output :
Traceback (most recent call last):
File "/home/de4570cca20263ac2c4149f435dba22c.py", line 12, in
print (object.name)
AttributeError: 'B' object has no attribute 'name'
Hybrid Inheritance
class Base1(object):
def __init__(self):
self.str1 = “UIT1"
print("Base1")
class Base2(object):
def __init__(self):
self.str2 = “UIT2"
print("Base2")
def printStrs(self):
print(self.str1, self.str2)
ob = Derived()
ob.printStrs()
# Constructor
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age
# To get name
def getAge(self):
return self.age
# Constructor
def __init__(self, name, age, address):
Child.__init__(self, name, age)
self.address = address
# To get address
def getAddress(self):
return self.address
# Driver code
g = GrandChild(“UIT1", 23, “Burdwan")
print(g.getName(), g.getAge(), g.getAddress())
object1 = D()
Output:
Component class object created...
Composite class object also created...
Composite class m2() method executed...
Component class m1() method executed...
Syntax:
import module
print(calc.add(10, 2))
Output:
12
# importing sys.path
print(sys.path)
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’,
‘/usr/lib/python3.8/lib-dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-
packages’, ‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-
packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’,
‘/home/nikhil/.ipython’]
# Sine of 2 radians
print(math.sin(2))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
Output:
3
0.401533172951
88.4917616788
True
Mod1.py
def gfg():
print("Welcome to GFG")
Mod2.py
def sum(a, b):
return a+b
mod1.gfg()
res = mod2.sum(1, 2)
print(res)
Output:
Welcome to GFG
3
We can also import the specific function also using the same
syntax.
Example: Import Specific function from the module
from mypckg.mod1 import gfg
from mypckg.mod2 import sum
gfg()
res = sum(1, 2)
print(res)
Output:
Welcome to GFG
3
You can put this into a new Python file called test_sum.py and
execute it again:
def test_sum():
assert sum([1, 2, 3]) == 6, "Should be 6"
if __name__ == "__main__":
test_sum()
print("Everything passed")
Now you have written a test case, an assertion, and an entry
point (the command line). You can now execute this at the
command line:
$ python test_sum.py
Everything passed
1 class TestGetAreaRectangle(unittest.TestCase):
2 def runTest(self):
3 rectangle = Rectangle(2, 3)
4 self.assertEqual(rectangle.get_area(), 6, "incorrect area")
1 ...
2 unittest.main()
Since the code returns the expected output for this case, it
returns that the tests run successfully, with the output:
1 .
2 ----------------------------------------------------------------------
3 Ran 1 test in 0.003s
4
5 OK
def get_area(self):
return self.width * self.height
1 class TestGetAreaRectangle(unittest.TestCase):
2 def test_normal_case(self):
3 rectangle = Rectangle(2, 3)
4 self.assertEqual(rectangle.get_area(), 6, "incorrect area")
5
6 def test_negative_case(self):
7 """expect -1 as output to denote error when looking at
8 negative area"""
9 rectangle = Rectangle(-1, 2)
self.assertEqual(rectangle.get_area(), -1, "incorrect
negative output")
Shell
To write tests, you just need to write functions with names
prefixed with “test,” and PyTest‟s test discovery procedure will be
able to find your tests, e.g.,
1 def test_normal_case(self):
2 rectangle = Rectangle(2, 3)
3 assert rectangle.get_area() == 6, "incorrect area"
project/
│
├── my_sum/
│ └── __init__.py
|
└── test.py
Output:
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
In the above example, the statements that can cause the error are
placed inside the try statement (second print statement in our case).
The second print statement tries to access the fourth element of the
list which is not there and this throws an exception. This exception
is then caught by the except statement.
def fun(a):
if a < 4:
Output:
Can't divide by zero
This is always executed
The output of the above code will simply line printed as “An
exception” but a Runtime error will also occur in the last due to
the raise statement in the last line. So, the output on your
command line will look like
Traceback (most recent call last):
File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in
<module>
raise NameError("Hi there") # Raise Error
NameError: Hi there
An exception
if x < 0:
raise Exception("Sorry, no numbers below zero")
# Constructor or Initializer
def __init__(self, value):
self.value = value
Output:
'A New Exception occurred: ', 6
Questions?