Module 4
Module 4
Module 4
Category : Minor
Offered by : Dept. of Computer Science and Engg.
Faculty in charge : Jaseela Beevi S
üClass - They are defined by the user. The class provide basic structure for an object.
üData Member - A variable defined in either a class or an object. It holds the data
associated with the class or object.
üInstance variable - A variable that is defined in a method; its scope is only within the
object that defines it.
üClass Variable - A variable that is defined in the class and can be used by all the
instances of the class.
Data Encapsulation:
• In OOP, restrictions can be imposed on the access to methods and variables. Such
restrictions can be used to avoid accidental modification in the data and are known as
Encapsulation.
Dept. of CSE, TKMCE 6
• Polymorphism
The term polymorphism means that the object of a class can have many different forms
to respond in different ways to any message or action.
• In python, as soon as we define a class, the iterpreter instantly creates an object that
has the same name as the class name.
• We can create more objects of the same class. With the help of objects, we can access
the attributes defined in the class.
1. Parameterized Constructor
2. Non-parameterized Constructor
def getNumber(self):
print(f'{self.real} + j{self.imag}')
num1 = ComplexNumber(2, 3)
num1.getNumber()
Output : 2+j3
Dept. of CSE, TKMCE 13
Example : Display Employee Details
class Employee:
def __init__(self, id, name): Output:
self.id = id
Id: 1
self.name = name
Name: john
Id: 2
def display(self):
Name: Anu
print("Id: %d\n Name: %s" % (self.id, self.name))
emp1.display()
emp2.display()
Dept. of CSE, TKMCE 14
Python Non-Parameterized Constructor Python Parameterized Constructor
The non-parameterized constructor uses when The parameterized constructor has multiple
we do not want to manipulate the value or the parameters along with the self.
constructor that has only self as an argument.
class Student:
class Student: def __init__(self, name):
def __init__(self): print("This is parameterized constructor")
print("This is non parameterized self.name = name
constructor")
def show(self):
def show(self, name): print("Hello ", self.name)
print("Hello ", name)
s1 = Student() s1 = Student("Rahul")
s1.show("Roshan") s1.show()
output: output:
This is non parameterized constructor This is parameterized constructor
Hello Roshan Hello Rahul
Dept. of CSE, TKMCE 15
Python Default Constructor
When we do not include the constructor in the class or forget to declare it, then that
becomes the default constructor. It does not perform any task but initializes the objects.
class Student:
name = "Jeevan"
rollno = 101
def show(self):
print("Name: ", self.name)
print("Roll No: ", self.rollno)
s1 = Student()
s1.show()
Output:
Name: Jeevan
Roll No: 101 Dept. of CSE, TKMCE 16
Example : The Student class
A course-management application needs to represent information about students in a
course. Each student has a name and a list of test scores. We can use these as the
attributes of a class named Student. The Student class should allow the user to view a
student’s name, view a test score at a given position (counting from 1), reset a test
score at a given position, view the highest test score, view the average test score, and
obtain a string representation of the student’s information.
Accessor Method: This method is used to access the state of the object i.e, the data
hidden in the object can be accessed from this method. However, this method cannot
change the state of the object, it can only access the data hidden. We can name these
methods with the word get.
Mutator Method: This method is used to mutate/modify the state of an object i.e, it
alters the hidden value of the data variable. It can set the value of a variable instantly
to a new value. This method is also called as update method. Moreover, we can name
these methods with the word set.
Dept. of CSE, TKMCE 21
Example : Accessors and Mutators
class Fruit:
def __init__(self, name):
self.name = name Output:
First fruit name: Apple
Second fruit name: Grape
def setFruitName(self, name):
self.name = name
def getFruitName(self):
return self.name
f1 = Fruit("Apple")
print("First fruit name: ", f1.getFruitName())
f1.setFruitName("Grape")
print("Second fruit name: ", f1.getFruitName())
Dept. of CSE, TKMCE 22
Inheritance in Python
• Inheritance is an important aspect of the object-oriented paradigm. Inheritance
provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.
• In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class.
Syntax:
class derived class name(base class):
<class-suite>
Person Student
Resident
Output:
Roshan
21
101
C1 = C()
class B: print(C1.getName())
def __init__(self):
self.name = "Richard"
self.id = 32 Output:
Richard
def getName(self):
return self.name Dept. of CSE, TKMCE 29
Method Resolution Order (MRO)
MRO works in a depth first left to right way. super() in the __init__ method indicates
the class that is in the next hierarchy. At first the the super() of C indicates A.
Then super in the constructor of A searches for its superclass. If it doesn’t find any, it
executes the rest of the code and returns. So the order in which constructors are called
here is:
C -> A -> B
class B: C1 = C()
def __init__(self): print(C1.getName())
super().__init__() print(C.__mro__)
self.name = 'Richard'
self.id = '32' Output : John
Dept. of CSE, TKMCE 31
Multilevel Inheritance
• This is achieved when a derived class inherits another derived class. There is no limit
on the number of levels up to which, the multi-level inheritance is achieved in python.
• Syntax
First
class class1:
<class-suite>
class class2(class1):
Second
<class suite>
class class3(class2):
<class suite> Third
class Second(First):
def second(self): Output:
print("I am the second class") I am the first class
I am the second class
I am the third class
class Third(Second):
def third(self):
print("I am the third class")
Output:
class Child2(Parent):
def func3(self): This function is in child1
print("This function is in This function is in Parent
child3") This function is in child3
Dept. of CSE, TKMCE 35
Hybrid Inheritance
• The hybrid inheritance is the combination of more than one type of inheritance. We
may use any combination as a single with multiple inheritances, multi-level with
multiple inheritances, etc.
B C
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname) Dept. of CSE, TKMCE 37
Polymorphism in Python
• The word polymorphism means having many forms. In programming, polymorphism
means same function name (but different signatures) being uses for different types.
print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))
Output:
This is a Rectangle
Area: 120
This is a geometric shape
Area: 130
Like in other programming languages, the child classes in Python also inherit methods
and attributes from the parent class. We can redefine certain methods and attributes
specifically to fit the child class, which is known as Method Overriding.
In Python, to override a method, you have to meet certain conditions, and they are:
• You can’t override a method within the same class. It means you have to do it in
the child class using the Inheritance concept.
• To override the Parent Class method, you have to create a method in the Child
class with the same name and the same number of parameters.
class Child(Parent):
def __init__(self): Output:
self.value = "Inside Child"
Inside Parent
def show(self): Inside Child
print(self.value)
• For defining abstract methods in an abstract class, method has to be decorated with
@abstractmethod decorator.
• From abc module @abstractmethod decorator has to be imported to use that
annotation.
• Abstract class can have both concrete methods as well as abstract methods.
• Generally abstract methods defined in abstract class don’t have any body but it
is possible to have abstract methods with implementation in abstract class.
• If any abstract method is not implemented by the derived class Python throws
an error.
• Two common kinds of errors that you may have to deal with are
üSyntax errors
üExceptions
Syntax Errors:
It occur when you type the code incorrectly.
Exceptions:
They are different from syntax errors. They occur during the execution of a program
when something unexpected happens.
• ValueError: This exception occurs when a function argument has the right type
but an inappropriate value.
• ZeroDivisionError: This exception is raised when you provide the second argument for
a division or modulo operation as zero.
• FileNotFoundError: This exception is raised when the file or directory that the program
requested does not exist
You will get Value Error on entering decimal number or string as input.
except ValueError:
print("The input was not an integer. Please try again...")
Output:
Please enter a number: a
The input was not an integer. Please try again...
Please enter a number: 2
Dividing 50 by 2 will give you: 25.0
Dept. of CSE, TKMCE 53
• If no exception was raised, the program skips the except clause and the rest of the
code executes normally.
• If an exception is raised, the program skips the remaining code inside the try clause
and the type of the exception is matched with the name of the exception after the
except keyword.
In case of a match, the code inside the except clause is executed
first, and then the rest of the code after the try clause is executed normally.
• When you enter an integer as an input, the program gives you the final result of the
division.
• When a non-integral value is provided, the program prints a message asking you to try
and enter an integer again.
• Note that this time, the program does not abruptly quit when you provide some
invalid input
• One possible use of catching all exceptions is to properly print out the exception error on
screen like the following code:
import math
import sys
try:
result = math.factorial(2.4)
except:
print("Something Unexpected has happened.",sys.exc_info()[0])
else:
print("The factorial is", result)
Dept. of CSE, TKMCE 55
Using the Else Clause
• The else clause is meant to contain code that needs to be executed if the try clause did
not raise any exceptions.
• if you decide to use an else clause, you should include it after all the except clauses but
before the finally block.
a = True
while a:
try:
x = int(input("Please enter a number: "))
except ValueError:
print("The input was not a valid integer. Please try again...")
else:
print("Dividing 50 by", x, "will give you :", 50 / x)
a = True
while a:
try:
x = int(input("Please enter a number: "))
except ValueError:
print("The input was not a valid integer. Please try again...")
else:
print("Dividing 50 by", x,"will give you :", 50/x)
finally:
print("Already did everything necessary.")
Dept. of CSE, TKMCE 57
Output:
• To raise an exception, the raise statement is used. The exception class name follows it.
• An exception can be provided with a value that can be given in the parenthesis.
• To access the value "as" keyword is used. "e" is used as a reference variable
which stores the value of the exception.
• We can pass the value to an exception to specify the exception type.
Output:
class customError(Exception):
pass
raise customError