0% found this document useful (0 votes)
2K views

Ds With Python Question Bank: Unit-1: Object-Oriented Concepts in Python 2M Questions

The document contains questions related to object-oriented concepts in Python like classes, objects, methods, inheritance, polymorphism, abstraction etc. and data structures and algorithms concepts like searching, sorting, linked lists. It has 2 sections - 2 million questions on OOP concepts in Python and 8 million questions covering method overloading, inheritance with examples, constructors, polymorphism, operator overloading, data structures and their applications etc. The questions range from basic to advanced level concepts and problems related to these topics.

Uploaded by

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

Ds With Python Question Bank: Unit-1: Object-Oriented Concepts in Python 2M Questions

The document contains questions related to object-oriented concepts in Python like classes, objects, methods, inheritance, polymorphism, abstraction etc. and data structures and algorithms concepts like searching, sorting, linked lists. It has 2 sections - 2 million questions on OOP concepts in Python and 8 million questions covering method overloading, inheritance with examples, constructors, polymorphism, operator overloading, data structures and their applications etc. The questions range from basic to advanced level concepts and problems related to these topics.

Uploaded by

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

DS WITH PYTHON QUESTION BANK

Unit-1: Object-Oriented Concepts in Python


2M Questions:
1. List out features of OOP’s in Python.
2. Define class with syntax.
3. Define Object with syntax.
4. Define method with syntax.
5. What is Inheritance
6. Define Polymorphism
7. Define Data Abstraction.
8. List out the areas in which data structures are applied extensively.
9. What is operator Overloading
10. What is Operator Overriding
11. Define constructor with syntax.
12. What is the use of __init__ method.
13. What is the use of self?
14. What is the name of the class to be imported to create an abstract class. Explain with
example.
15. Distinguish between a linear and nonlinear data structure.
16. What is operator overloading?

8M Questions:
1. Write the differences between method overloading and method overriding. Explain with
example program
2. Write a program to demonstrate student class and calculate CGPA of student and display
the result.
3. Define Inheritance. Explain each category of inheritance with an example program.
4. What is a constructor? Write a program for demonstrate different types of constructor
5. Explain in detail about Multiple Inheritance and Multilevel Inheritance along with an
example python program.
6. a) What is a Constructor? Is Constructor Overloading possible in Python? Explain.
b) Differences between Parameterized and Default constructors.
7. Define Polymorphism and explain in detail about Runtime Polymorphism with an example
python program.
8. What is Operator Overloading? Explain Overloading in Comparison operator (< less than)
with an example python program.
9. Define data structure. Discuss different types of data structure and their implementation
applications.
10. Explain the features of OOPs? Describe Encapsulation, Inheritance and Polymorphism.
11. Explain in detail about Abstraction with an example program.
12. Differences between Run time Polymorphism and Compile time polymorphism.
13. What is Encapsulation. Explain with an example program.
14. Write a python program which calculates areas of square, rectangle, circle using
Abstraction concept.
ALL LAB PROGRAMS OF UNIT-1

Unit-2 : Searching, Sorting, Linked Lists


2M Questions
1. Define Internal Sorting
2. Define External Sorting
3. What is need of Priority Queues.
4. What is a Circular Linked list.
5. Define Linked list.
6. What is deque.
7. List three differences between Bubble sort and selection sort.
8. List three differences between selection sort and insertion sort.
9. How many iterations are possible to sort a list of 120 numbers using Bubble Sort technique?
10. How many iterations are possible to sort a list of 120 numbers using Insertion Sort technique?
11. How many iterations are possible to sort a list of 120 numbers using Selection Sort technique?
12. What is Sorting? List at least 3 types of sorting techniques.
13. In Which type of Linked List there will not be None/null pointer in the address/Next field.
14. List the basic operations carried out in a linked list
15. How many types of Searching techniques we have. Among them which is the best
technique.

8M Questions:
1. Explain the following searching techniques with examples 1.Linear search 2.Binary
search
2. What is a single linked list? Explain Different operations on single linked list
3. Write algorithm and program for implementing Binary search
4. Write algorithm and program for implementing Linear search
5. Write a program for implementing a singly linked list.
6. Explain in detail about Insertion Sort with an example python program.
7. Explain in detail about Selection Sort with an example python program.
8. Explain in detail about Bubble Sort with an example python program.
9. Write a Python program to Insert a node at the beginning and end and to delete a node at the
beginning and end of circular linked list.
10. Write a Python program to Insert a node at the beginning and end and to delete a node at the
beginning and end of doubly linked list.
DS WITH PYTHON QUESTION BANK
Unit-1: Object-Oriented Concepts in
Python 2M Questions:
1. List out features of OOP’s in Python.
A)
The 4 Principles Of Object-Oriented Programming. Encapsulation,
Abstraction,Polymorphism, Inheritance.
Major Python OOP's concept-
Class.
Object.
Method.
Inheritance.
Encapsulation.
Polymorphism.
Data Abstraction.
2. Define class with syntax.
A)
A class is a code template for creating objects. Objects have member
variables and have behaviour associated with them. In python a class is
created by the keyword class.An object is created using the constructor of
the class. This object will then be called the instance of the class.A Class
is like an object constructor, or a "blueprint" for creating objects.

3. Define Object with syntax.


A)
Python is an object-oriented programming language. Everything is in
Python treated as an object, including variable, function, list, tuple,
dictionary, set, etc. Every object belongs to its class. For example - An
integer variable belongs to integer class. An object is a real-life entity.A
syntax object is like an S-expression, but nodes in a syntax object have
source-location and binding information.

4. Define method with syntax.


A)
A method is a function that “belongs to” an object. (In Python, the term
method is not unique to class instances: other object types can have
methods as well. For example, list objects have methods called append,
insert, remove, sort, and so on.Methods are similar to functions: they're
declared with the fn keyword and their name, they can have parameters
and a return value, and they contain some code that is run when they're
called from somewhere else.
5. What is Inheritance
A)
Inheritance is a powerful feature in object oriented programming. It refers
to defining a new class with little or no modification to an existing class.
The new class is called derived (or child) class and the one from which it
inherits is called the base (or parent) class.

6. Define Polymorphism
A)
Polymorphism is a concept of object oriented programming, which means
multiple forms or more than one form. Polymorphism enables using a
single interface with input of different datatypes, different class or may be
for different number of inputs.

7. Define Data Abstraction.


A)
Abstraction in python is the concept of object oriented programming,
where user is unaware the complex implementation detail of functionality
and internal working, whereas user is only able to see the basic
functionalities and internal details are hidden. Data abstraction refers to
providing only essential information about the data to the outside world,
hiding the background details or implementation.

8. List out the areas in which data structures are applied extensively.
A)
Data structure is applied in the following areas: numerical analysis,
operating system,A.I., compiler design, database management, graphics,
and statistical analysis, to name a few.
● Compiler Design,
● Operating System,
● Database Management System,
● Statistical analysis package,
● Numerical Analysis,
● Graphics,
● Artificial Intelligence,
● and Simulation.

9. What is operator Overloading


A)
Operator overloading in Python is the ability of a single operator to perform
more than one operation based on the class (type) of operands. For
example, the + operator can be used to add two numbers, concatenate
two strings or merge two lists Operator overloading facilitates the
specification of user-defined implementation for operations wherein one or
both operands are of user-defined class or structure type. This helps user-
defined types to behave much like the fundamental primitive data types.
10. What is Operator Overriding
A)
Operator overloading is a technique by which operators used in a
programming language are implemented in user-defined types with
customized logic that is based on the types of arguments passed.

Operator overloading facilitates the specification of user-defined


implementation for operations wherein one or both operands are of user-
defined class or structure type. This helps user-defined types to behave
much like the fundamental primitive data types.
11. Define constructor with syntax.
A)
The task of constructors is to initialize(assign values) to the data members
of the class when an object of class is created.In Python the __init__()
method is called the constructor and is always called when an object is
created. Syntax of constructor declaration : def __init__(self): # body of the
constructor.

12. What is the use of init__ method.


A)
The __init__ method is similar to constructors in C++ and Java .
Constructors are used to initialize the object's state. The task of
constructors is to initialize(assign values) to the data members of the class
when an object of class is created.

13. What is the use of self?


A)
The use of self makes it easier to distinguish between instance attributes
(and methods) from local variables. You could declare variables within a
class without using the self reference , but then those variables would be
shared by all instances of that class, which may not be what you intended.

14. What is the name of the class to be imported to create an abstract


class.Explain with example.
A)
An abstract class can be considered as a blueprint for other classes. It
allows you to create a set of methods that must be created within any child
classes built from the abstract class. A class which contains one or more
abstract methods is called an abstract class.
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass
class Triangle(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 3 sides")
class Pentagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 5 sides")
# Driver code
R = Triangle()
R.noofsides()
R = Pentagon()
R.noofsides()
Output:
I have 3 sides
I have 5 sides

15. Distinguish between a linear and nonlinear data structure.


A)
S.NO Linear Data Structure Non-linear Data Structure
1 In a linear data structure, data In a non-linear data structure, data
elements are arranged in a linear elements are attached in
order where each and every hierarchically manner.
elements are attached to its
previous and next adjacent.
2 In linear data structure, single level Whereas in non-linear data
is involved. structure, multiple levels are
involved.
3 Its implementation is easy in While its implementation is
comparison to non-linear data complex in comparison to linear
structure. data structure.
4 In linear data structure, data While in non-linear data structure,
elements can be traversed in a data elements can’t be traversed
single run only. in a single run only.

5 In a linear data structure, memory While in a non-linear data


is not utilized in an efficient way. structure, memory is utilized in an
efficient way.
6 Its examples are: array, stack, While its examples are: trees and
queue, linked list, etc. graphs.
7 Applications of linear data Applications of non-linear data
structures are mainly in application structures are in Artificial
software development. Intelligence and image processing.
16. What is operator overloading?
A)
Operator overloading is a technique by which operators used in a
programming language are implemented in user-defined types with
customized logic that is based on the types of arguments passed.

8M Questions:
1. Write the differences between method overloading and method
overriding. Explain with example program
A) Method Overloading:
Method Overloading is an example of Compile time polymorphism. In
this, more than one method of the same class shares the same method
name having different signatures. Method overloading is used to add
more to the behavior of methods and there is no need of more than one
class for method overloading.
Note: Python does not support method overloading. We may overload
the methods but can only use the latest defined method.
Example:
# Function to take multiple arguments
def add(datatype, *args):

# if datatype is int
# initialize answer as 0
if datatype =='int':
answer = 0

# if datatype is str
# initialize answer as ''
if datatype =='str':
answer =''

# Traverse through the arguments


for x in args:

# This will do addition if the


# arguments are int. Or concatenation
# if the arguments are str
answer = answer + x

print(answer)

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

# String
add('str', 'Hi ', 'Geeks')
Output:

11
Hi Geeks
Method Overriding:
Method overriding is an example of run time polymorphism. In this, the
specific implementation of the method that is already provided by the
parent class is provided by the child class. It is used to change the
behavior of existing methods and there is a need for at least two classes
for method overriding. In method overriding, inheritance always required
as it is done between parent class(superclass) and child class(child class)
methods.
Example of Method Overriding in python:

class A:

def fun1(self):
print('feature_1 of class A')

def fun2(self):
print('feature_2 of class A')

class B(A):

# Modified function that is


# already exist in class A
def fun1(self):
print('Modified feature_1 of class A by class B')

def fun3(self):
print('feature_3 of class B')

# Create instance
obj = B()

# Call the override function


obj.fun1()
Output:

Modified feature_1 of class A by class B

2. Write a program to demonstrate student class and calculate


CGPA of student and display the result.
A)# Python code to find student grade report

class Student:

#Declaring class for student related variables and methods

def __init__(self):

#Initializing empty variables for student class to be used later on

self.__roll=0

self.__name=””

self.__marks=[]

self.__total=0

self.__per=0

self.__grade=””

self.__result=””

def setStudent(self):

#Creating setStudent method to set the values assigned by user

self.__roll=int(input(“Enter Roll: “))

self.__name=input(“Enter Name: “)

print(“Enter marks of 5 subjects: “)

for i in range(5):

self.__marks.append(int(input(“Subject “+str(i+1)+”: “)))


def Total(self):

#Creating Total method to get the total marks of student

for x in self.__marks:

self.__total+=x

def Percentage(self):

#Creating method Percentage to get the percentage of student

self.__per=self.__total/5

def Grade(self):

#Creating Grade method to give Grade class to student

if self.__per>=85:

self.__grade=”S”

elif self.__per>=75:

self.__grade=”A”

elif self.__per>=65:

self.__grade=”B”

elif self.__per>=55:

self.__grade=”C”

elif self.__per>=50:

self.__grade=”D”

else:

self.__grade=”F”

def Result(self):

#Creating Result to showcase the result of student

count=0
for x in self.__marks:

if x>=50:

count+=1

if count==5:

self.__result=”PASS”

elif count>=3:

self.__result=”COMP.”

else:

self.__result=”FAIL”

def printStudent(self):

#Creating Print method to print the details of student after calculation

self.Total()

self.Percentage()

self.Grade()

self.Result()

print(“Roll
No:”,self.__roll,”\t”,”Name:”,self.__name,”\t”,”Total:”,self.__total,”\t”,”Percen
tage:”,self.__per,”\t”,”Grade:”,self.__grade,”\t”,”Result Class:”,self.__result)

def main():

#Using main function to call the methods of student class

#Student object

s=Student()

s.setStudent()

s.printStudent()

if __name__==”__main__”:
main()

Output :

Enter Roll: 12

Enter Name: EdTech

Enter marks of 5 subjects:

Subject 1: 70

Subject 2: 75

Subject 3: 80
Subject 4: 85

Subject 5: 90

Roll No: 12

Name: EdTech Total: 400 Percentage: 80.0 Grade: A

Result Class: PASS

3. Define Inheritance. Explain each category of inheritance with an


example program.
A) Inheritance is the capability of one class to derive or inherit the
properties from another class.
Different forms of Inheritance:
1. Single inheritance: When a child class inherits from only one parent
class, it is called single inheritance.

# Python program to demonstrate


# single inheritance

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")

# Driver's code
object = Child()
object.func1()
object.func2()
Output:

This function is in parent class.


This function is in child class.

2. Multiple inheritance: When a child class inherits from multiple parent


classes, it is called multiple inheritance.
Unlike Java and like C++, Python supports multiple inheritance. We
specify all parent classes as a comma-separated list in the bracket.

# Python example to show the working of


multiple
# inheritance
class Base1(object):
def __init__(self):
self.str1 = "Geek1"
print("Base1")

class Base2(object):
def __init__(self):
self.str2 = "Geek2"
print("Base2")

class Derived(Base1, Base2):


def __init__(self):

# Calling constructors of Base1


# and Base2 classes
Base1.__init__(self)
Base2.__init__(self)
print("Derived")

def printStrs(self):
print(self.str1, self.str2)
ob = Derived()
ob.printStrs()
Output:
Base1
Base2
Derived
Geek1 Geek2

3. Multilevel inheritance: When we have a child and grandchild


relationship.

# A Python program to demonstrate inheritance

# Base or Super class. Note object in bracket.


# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"
class Base(object):

# Constructor
def __init__(self, name):
self.name = name

# To get name
def getName(self):
return self.name

# Inherited or Sub class (Note Person in bracket)


class Child(Base):

# Constructor
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age

# To get name
def getAge(self):
return self.age

# Inherited or Sub class (Note Person in bracket)


class GrandChild(Child):

# 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("Geek1", 23, "Noida")
print(g.getName(), g.getAge(), g.getAddress())
Output:
Geek1 23 Noida

4. Hierarchical inheritance More than one derived classes are created


from a single base.

# Python program to demonstrate


# Hierarchical inheritance

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")

# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.

5. Hybrid inheritance: This form combines more than one form of


inheritance. Basically, it is a blend of more than one type of inheritance.

# Python program to demonstrate


# hybrid inheritance

class School:
def func1(self):
print("This function is in school.")

class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.")

class Student3(Student1, School):


def func4(self):
print("This function is in student 3.")

# Driver's code
object = Student3()
object.func1()
object.func2()
Output:
This function is in school.
This function is in student 1.

5. What is a constructor? Write a program for demonstrate different


types of constructor
A)Constructors are generally used for instantiating an object. The task of
constructors is to initialize(assign values) to the data members of the
class when an object of the class is created. In Python the __init__()
method is called the constructor and is always called when an object is
created.
Syntax of constructor declaration :
def __init__(self):
# body of the constructor
Types of constructors :
 default constructor: The default constructor is a simple
constructor which doesn’t accept any arguments. Its definition has
only one argument which is a reference to the instance being
constructed.
 parameterized constructor: constructor with parameters is known
as parameterized constructor. The parameterized constructor takes its
first argument as a reference to the instance being constructed known
as self and the rest of the arguments are provided by the programmer.
Example of default constructor :

class GeekforGeeks:

# default constructor
def __init__(self):
self.geek = "GeekforGeeks"

# a method for printing data members


def print_Geek(self):
print(self.geek)

# creating object of the class


obj = GeekforGeeks()

# calling the instance method using the object obj


obj.print_Geek()
Output :
GeekforGeeks
Example of the parameterized constructor :

class Addition:
first = 0
second = 0
answer = 0

# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s

def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " + str(self.answer))

def calculate(self):
self.answer = self.first + self.second

# creating object of the class


# this will invoke parameterized constructor
obj = Addition(1000, 2000)

# perform Addition
obj.calculate()

# display result
obj.display()
Output :
First number = 1000
Second number = 2000
Addition of two numbers = 3000

6. Explain in detail about Multiple Inheritance and Multilevel


Inheritance along with an example python program.
A)2. Multiple inheritance: When a child class inherits from multiple
parent classes, it is called multiple inheritance.
Unlike Java and like C++, Python supports multiple inheritance. We
specify all parent classes as a comma-separated list in the bracket.

# Python example to show the working of


multiple
# inheritance
class Base1(object):
def __init__(self):
self.str1 = "Geek1"
print("Base1")

class Base2(object):
def __init__(self):
self.str2 = "Geek2"
print("Base2")

class Derived(Base1, Base2):


def __init__(self):

# Calling constructors of Base1


# and Base2 classes
Base1.__init__(self)
Base2.__init__(self)
print("Derived")

def printStrs(self):
print(self.str1, self.str2)

ob = Derived()
ob.printStrs()
Output:
Base1
Base2
Derived
Geek1 Geek2

3. Multilevel inheritance: When we have a child and grandchild


relationship.

# A Python program to demonstrate inheritance

# Base or Super class. Note object in bracket.


# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"
class Base(object):

# Constructor
def __init__(self, name):
self.name = name

# To get name
def getName(self):
return self.name

# Inherited or Sub class (Note Person in bracket)


class Child(Base):

# Constructor
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age

# To get name
def getAge(self):
return self.age

# Inherited or Sub class (Note Person in bracket)


class GrandChild(Child):

# 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("Geek1", 23, "Noida")
print(g.getName(), g.getAge(), g.getAddress())
Output:
Geek1 23 Noida

7. a) What is a Constructor? Is Constructor Overloading possible in


Python? Explain.
b) Differences between Parameterized and Default constructors.
A)a)Constructors are generally used for instantiating an object. The task
of constructors is to initialize(assign values) to the data members of the
class when an object of the class is created. In Python the __init__()
method is called the constructor and is always called when an object is
created.
Syntax of constructor declaration :
def __init__(self):
# body of the constructor

Python does not support method overloading, that is, it is not possible to define more
than one method with the same name in a class in python. This is because method
arguments in python do not have a type. A method accepting one argument can be
called with an integer value, a string or a double.
B)
8. Define Polymorphism and explain in detail about Runtime
Polymorphism with an example python program.
A)
Polymorphism:-
The word polymorphism means having many forms. In programming,
polymorphism means the same function name (but different signatures)
being used for different types.
Runtime Polymorphism:
 It is called “dynamic binding”.
 It is method “overriding technique”.
 Overriding is the concept of defining a method in Child class with the
same name and same set of arguments in Parent class method.
 A Child object can shows the functionality of Parent and Child.
Hence it is called Polymorphic

class Grand:
def fun(self):
print("Grand")
return

class Parent(Grand):
def fun(self):
print("Parent")
return

class Child(Parent):
def fun(self):
print("Child")
return

class Override:
def main():
obj = Child()
obj.fun()
super(Child,obj).fun()
super(Parent,obj).fun()
return

Override.main()
9. What is Operator Overloading? Explain Overloading in
Comparison operator (< less than) with an example python program.
A)
Operator Overloading:-
Operator Overloading means giving extended meaning beyond their
predefined operational meaning. For example operator + is used to add
two integers as well as join two strings and merge two lists. It is
achievable because ‘+’ operator is overloaded by int class and str
class. You might have noticed that the same built-in operator or
function shows different behavior for objects of different classes, this is
called Operator Overloading.
Overloading in Comparison operator (< less than) example:-
# Python program to overload
equality
# and less than operators

class A:
def __init__(self, a):
self.a = a
def __lt__(self, other):
if(self.a<other.a):
return "ob1 is lessthan
ob2"
else:
return "ob2 is less than
ob1"
def __eq__(self, other):
if(self.a == other.a):
return "Both are equal"
else:
return "Not equal"

ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2)

ob3 = A(4)
ob4 = A(4)
print(ob1 == ob2)
Output :

ob1 is lessthan ob2


Not equal

10. Define data structure. Discuss different types of data structure


and their implementation applications.
A)
Data structure:-
A data structure is a specialized format for organizing, processing,
retrieving and storing data. There are several basic and advanced types
of data structures, all designed to arrange data to suit a specific purpose.
Data structures make it easy for users to access and work with the data
they need in appropriate ways. Most importantly, data structures frame
the organization of information so that machines and humans can better
understand it.
Different types of data structure:-
The data structure type used in a particular situation is determined by the
type of operations that will be required or the kinds of algorithms that will
be applied. The various data structure types include the following:

 Array.

Applications: Implementation of other data structures, Execution of


matrices and vectors, Dynamic memory allocation, Pointer container,
Control tables

 Stack.
Applications: Evaluation of expressions, Backtracking, Runtime memory
management, Arrangement of books in a library
 Queue.
Applications: Disk scheduling, CPU scheduling, File IO, Data
transmission
 Linked list.
Applications: Representation of sparse matrices, Non-contiguous data
storage, Implementation of non-binary tree or other data structures,
Dynamic memory management, Equalizing parenthesis, Symbol tables
 Tree.
Applications: Representation of data lists, Quickly accessible data
storage, Representation of hierarchal data, Routing of algorithms
 Graph.
Applications: Computer networking, Problem solutions involving ‘Depth-
First’ search or ‘Breadth-First’ search algorithms, Representation of
matrices, Study of molecular interactions in Chemistry
 File
Applications: Implementation of computer programs, Data comparison,
Storage of data having varying data types
 Hash table.
Applications: Unique data representation, Implementation of caches,
Array association, Locating entries in a table, Representation of objects,
Database indexing

11. Explain the features of OOP's? Describe Encapsulation,


Inheritance and Polymorphism.
A)

Object-Oriented programming is a programming-paradigm revolving


around the definition of objects that send messages to each other. These
objects also contain it’s own public and internal interfaces, which I will
highlight later in this article.
Encapsulation:

Encapsulation is one of the fundamental concepts in object-oriented


programming (OOP). It describes the idea of wrapping data and the
methods that work on data within one unit. This puts restrictions on
accessing variables and methods directly and can prevent the accidental
modification of data. To prevent accidental change, an object’s variable
can only be changed by an object’s method. Those types of variables are
known as private variable.
A class is an example of encapsulation as it encapsulates all the data
that is member functions, variables, etc.

class Person:
def __init__(self, name, age=0):
self.name = name
self.age = age

def display(self):
print(self.name)
print(self.age)

person = Person('Dev', 30)


#accessing using class method
person.display()
#accessing directly from outside
print(person.name)
print(person.age)
Output
Dev
30
Dev
30

Python Inheritance

Inheritance enables us to define a class that takes all the functionality from a
parent class and allows us to add more. In this tutorial, you will learn to use
inheritance in Python.
Inheritance in Python

Inheritance is a powerful feature in object oriented programming.

It refers to defining a new class with little or no modification to an existing


class. The new class is called derived (or child) class and the one from
which it inherits is called the base (or parent) class.

Python Inheritance Syntax

class BaseClass:

Body of base class

class DerivedClass(BaseClass):

Body of derived class

Derived class inherits features from the base class where new features can
be added to it. This results in re-usability of code.

class Person(object):

# Constructor

def __init__(self, name):

self.name = name

# To get name

def getName(self):

return self.name

# To check if this person is an employee


def isEmployee(self):

return False

# Inherited or Subclass (Note Person in bracket)

class Employee(Person):

# Here we return true

def isEmployee(self):

return True

# Driver code

emp = Person("Geek1") # An Object of Person

print(emp.getName(), emp.isEmployee())

emp = Employee("Geek2") # An Object of Employee

print(emp.getName(), emp.isEmployee())

Output:
Geek1 False
Geek2 True
polymorphism

The literal meaning of polymorphism is the condition of occurrence in


different forms.

Polymorphism is a very important concept in programming. It refers to the


use of a single type entity (method, operator or object) to represent different
types in different scenarios.

class Cat:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Meow")

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print(f"I am a dog. My name is {self.name}. I am {self.age} years
old.")

def make_sound(self):
print("Bark")

cat1 = Cat("Kitty", 2.5)


dog1 = Dog("Fluffy", 4)

for animal in (cat1, dog1):


animal.make_sound()
animal.info()
animal.make_sound()

Output
Meow
I am a cat. My name is Kitty. I am 2.5 years old.
Meow
Bark
I am a dog. My name is Fluffy. I am 4 years old.
Bark

12. Explain in detail about Abstraction with an example program.


A)
Abstraction in Python

Abstraction is used to hide the internal functionality of the function from the
users. The users only interact with the basic implementation of the
function, but inner working is hidden. User is familiar with that "what
function does" but they don't know "how it does."

In Python, an abstraction is used to hide the irrelevant data/class in order


to reduce the complexity. It also enhances the application efficiency. Next,
we will learn how we can achieve abstraction using the Python program.

Abstraction classes in Python

In Python, abstraction can be achieved by using abstract classes and


interfaces.

A class that consists of one or more abstract method is called the abstract
class. Abstract methods do not contain their implementation. Abstract
class can be inherited by the subclass and abstract method gets its
definition in the subclass. Abstraction classes are meant to be the
blueprint of the other class. An abstract class can be useful when we are
designing large functions. An abstract class is also helpful to provide the
standard interface for different implementations of components. Python
provides the abc module to use the abstraction in the Python program.
Let's see the following syntax.

Syntax

1. from abc import ABC


2. class ClassName(ABC):

Example -

1. # Python program demonstrate


2. # abstract base class work
3. from abc import ABC, abstractmethod
4. class Car(ABC):
5. def mileage(self):
6. pass
7.
8. class Tesla(Car):
9. def mileage(self):
10. print("The mileage is 30kmph")
11. class Suzuki(Car):
12. def mileage(self):
13. print("The mileage is 25kmph ")
14. class Duster(Car):
15. def mileage(self):
16. print("The mileage is 24kmph ")
17.
18. class Renault(Car):
19. def mileage(self):
20. print("The mileage is 27kmph ")
21.
22. # Driver code
23. t= Tesla ()
24. t.mileage()
25.
26. r = Renault()
27. r.mileage()
28.
29. s = Suzuki()
30. s.mileage()
31. d = Duster()
32. d.mileage()

Output:

The mileage is 30kmph


The mileage is 27kmph
The mileage is 25kmph
The mileage is 24kmph

13. Differences between Run time Polymorphism and Compile time


polymorphism.
A)
Compile time Polymorphism Run time Polymorphism
In Compile time Polymorphism, call is In Run time Polymorphism, call
resolved by the compiler. is not resolved by the compiler.
It is also known as Static binding, Early It is also known as Dynamic binding, Late
binding and overloading as well. binding and overriding as well.
Overloading is compile time polymorphism Overriding is run time polymorphism
where more than one methods share the having same method with same parameters
same name with different parameters or or signature, but associated in a class & its
signature and different return type. subclass.
It is achieved by function overloading It is achieved by virtual
and operator overloading. functions and pointers.
It provides fast execution because known It provides slow execution as compare to
early at compile time. early binding because it is known at
runtime.
Compile time polymorphism is less Run time polymorphism is more flexible as
flexible as all things execute at compile all things execute at run time.
time.

14. What is Encapsulation. Explain with an example program.

A)

Encapsulation:

Encapsulation is one of the fundamental concepts in object-oriented


programming (OOP). It describes the idea of wrapping data and the
methods that work on data within one unit. This puts restrictions on
accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an
object’s variable can only be changed by an object’s method. Those
types of variables are known as private variable.
A class is an example of encapsulation as it encapsulates all the data
that is member functions, variables, etc.

class Person:
def __init__(self, name, age=0):
self.name = name
self.age = age

def display(self):
print(self.name)
print(self.age)

person = Person('Dev', 30)


#accessing using class method
person.display()
#accessing directly from outside
print(person.name)
print(person.age)
Output
Dev
30
Dev
30

15. Write a python program which calculates areas of square,


rectangle, circle using Abstraction concept.
A)

You might also like