0% found this document useful (0 votes)
12 views22 pages

Python Interview

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
12 views22 pages

Python Interview

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

PYTHON INTERVIEW THEORY

QUESTIONS
GENERAL CONCEPTS

1. What is Python? List some popular applications of Python in the world of


technology.
Python is a widely-used general-purpose, high-level programming language. It
was created by Guido van Rossum in 1991 and further developed by the Python
Software Foundation. It was designed with an emphasis on code readability, and
its syntax allows programmers to express their concepts in fewer lines of code.
It is used for:
 System Scripting
 Web Development
 Game Development
 Software Development
 Complex Mathematics

2. What are the benefits of using Python language as a tool in the present
scenario?
The following are the benefits of using Python language:
 Object-Oriented Language
 High-Level Language
 Dynamically Typed language
 Extensive support Libraries
 Presence of third-party modules
 Open source and community development
 Portable and Interactive
 Portable across Operating systems

3. Is Python a compiled language or an interpreted language?


Actually, Python is a partially compiled language and partially interpreted
language. The compilation part is done first when we execute our code and this
will generate byte code internally this byte code gets converted by the Python
virtual machine(p.v.m) according to the underlying platform(machine+operating
system).

4. What does the ‘#’ symbol do in Python?


‘#’ is used to comment on everything that comes after on the line.

5. What is the difference between a Mutable datatype and an Immutable


data type?
Mutable data types can be edited i.e., they can change at runtime. Eg – List,
Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at runtime. Eg –
String, Tuple, etc.

6. How are arguments passed by value or by reference in Python?


Everything in Python is an object and all variables hold references to the objects.
The reference values are according to the functions; as a result, you cannot
change the value of the references. However, you can change the objects if it is
mutable.

7. What is the difference between a Set and Dictionary?


The set is an unordered collection of data types that is iterable, mutable and has
no duplicate elements. A dictionary in Python is an ordered collection of data
values, used to store data values like a map.

8. What is List Comprehension? Give an Example.


List comprehension is a syntax construction to ease the creation of a list based on
existing iterable.
For Example:
my_list = [i for i in range(1, 10)]

9. What is a lambda function?


A lambda function is an anonymous function. This function can have any number
of parameters but, can have just one statement. For Example:
a = lambda x, y : x*y
print(a(7, 19))
10. What is a pass in Python?
Pass means performing no operation or in other words, it is a placeholder in the
compound statement, where there should be a blank left and nothing has to be
written there.

11. What is the difference between / and // in Python?


/ represents precise division (result is a floating point number) whereas //
represents floor division (result is an integer). For Example:
5//2 = 2
5/2 = 2.5

12. How is Exceptional handling done in Python?


There are 3 main keywords i.e. try, except, and finally which are used to catch
exceptions and handle the recovering mechanism accordingly. Try is the block of
a code that is monitored for errors. Except block gets executed when an error
occurs.
The beauty of the final block is to execute the code after trying for an error. This
block gets executed irrespective of whether an error occurred or not. Finally,
block is used to do the required cleanup activities of objects/variables.

13. What is swapcase function in Python?


It is a string’s function that converts all uppercase characters into lowercase and
vice versa. It is used to alter the existing case of the string. This method creates a
copy of the string which contains all the characters in the swap case. For
Example:
string = "GeeksforGeeks"
string.swapcase() ---> "gEEKSFORgEEKS"

14. Difference between for loop and while loop in Python


The “for” Loop is generally used to iterate through the elements of various
collection types such as List, Tuple, Set, and Dictionary. Developers use a “for”
loop where they have both the conditions start and the end. Whereas, the “while”
loop is the actual looping feature that is used in any other programming language.
Programmers use a Python while loop where they just have the end conditions.

15. Can we Pass a function as an argument in Python?


Yes, Several arguments can be passed to a function, including objects, variables
(of the same or distinct data types), and functions. Functions can be passed as
parameters to other functions because they are objects. Higher-order functions are
functions that can take other functions as arguments.

16. What are *args and *kwargs?


To pass a variable number of arguments to a function in Python, use the special
syntax *args and **kwargs in the function specification. It is used to pass a
variable-length, keyword-free argument list. By using the *, the variable we
associate with the * becomes iterable, allowing you to do operations on it such as
iterating over it and using higher-order operations like map and filter.

17. Is Indentation Required in Python?


Yes, indentation is required in Python. A Python interpreter can be informed that
a group of statements belongs to a specific block of code by using Python
indentation. Indentations make the code easy to read for developers in all
programming languages but in Python, it is very important to indent the code in a
specific order.

18. What is Scope in Python?


The location where we can find a variable and also access it if required is called
the scope of a variable.
 Python Local variable: Local variables are those that are initialized within a
function and are unique to that function. It cannot be accessed outside of the
function.
 Python Global variables: Global variables are the ones that are defined and
declared outside any function and are not specified to any function.
 Module-level scope: It refers to the global objects of the current module
accessible in the program.
 Outermost scope: It refers to any built-in names that the program can call.
The name referenced is located last among the objects in this scope.

19. What is docstring in Python?


Python documentation strings (or docstrings) provide a convenient way of
associating documentation with Python modules, functions, classes, and methods.
 Declaring Docstrings: The docstrings are declared using ”’triple single
quotes”’ or “””triple double quotes””” just below the class, method, or
function declaration. All functions should have a docstring.
 Accessing Docstrings: The docstrings can be accessed using the __doc__
method of the object or using the help function.

20. What is a dynamically typed language?


Typed languages are the languages in which we define the type of data type and it
will be known by the machine at the compile-time or at runtime. Typed languages
can be classified into two categories:
 Statically typed languages: In this type of language, the data type of a
variable is known at the compile time which means the programmer has to
specify the data type of a variable at the time of its declaration.
 Dynamically typed languages: These are the languages that do not require
any pre-defined data type for any variable as it is interpreted at runtime by the
machine itself. In these languages, interpreters assign the data type to a
variable at runtime depending on its value.

21. What is a break, continue, and pass in Python?


The break statement is used to terminate the loop or statement in which it is
present. After that, the control will pass to the statements that are present after the
break statement, if available.
Continue is also a loop control statement just like the break statement. continue
statement is opposite to that of the break statement, instead of terminating the
loop, it forces to execute the next iteration of the loop.
Pass means performing no operation or in other words, it is a placeholder in the
compound statement, where there should be a blank left and nothing has to be
written there.

22. What are Built-in data types in Python?


The following are the standard or built-in data types in Python:
 Numeric: The numeric data type in Python represents the data that has a
numeric value. A numeric value can be an integer, a floating number, a
Boolean, or even a complex number.
 Sequence Type: The sequence Data Type in Python is the ordered collection
of similar or different data types. There are several sequence types in Python:
o Python String
o Python List
o Python Tuple
o Python range
 Mapping Types: In Python, hashable data can be mapped to random objects
using a mapping object. There is currently only one common mapping type,
the dictionary, and mapping objects are mutable.
o Python Dictionary
 Set Types: In Python, a Set is an unordered collection of data types that is
iterable, mutable, and has no duplicate elements. The order of elements in a
set is undefined though it may consist of various elements.

23. How do you floor a number in Python?


The Python math module includes a method that can be used to calculate the floor
of a number.
 floor() method in Python returns the floor of x i.e., the largest integer not
greater than x.
 Also, The method ceil(x) in Python returns a ceiling value of x i.e., the
smallest integer greater than or equal to x.

24. What is the difference between xrange and range functions?


range() and xrange() are two functions that could be used to iterate a certain
number of times in for loops in Python. In Python 3, there is no xrange, but the
range function behaves like xrange in Python 2.
 range() – This returns a list of numbers created using the range() function.
 xrange() – This function returns the generator object that can be used to
display numbers only by looping. The only particular range is displayed on
demand and hence called lazy evaluation.

25. What is Dictionary Comprehension? Give an Example


Dictionary Comprehension is a syntax construction to ease the creation of a
dictionary based on the existing iterable.
For Example: my_dict = {i:i+7 for i in range(1, 10)}

26. Is Tuple Comprehension? If yes, how, and if not why?


(i for i in (1, 2, 3))

Tuple comprehension is not possible in Python because it will end up in a


generator, not a tuple comprehension.

27. Differentiate between List and Tuple?


Let’s analyze the differences between List and Tuple:
List
 Lists are Mutable datatype.
 Lists consume more memory
 The list is better for performing operations, such as insertion and deletion.
 The implication of iterations is Time-consuming
Tuple
 Tuples are Immutable datatype.
 Tuple consumes less memory as compared to the list
 A Tuple data type is appropriate for accessing the elements
 The implication of iterations is comparatively Faster

28. What is the difference between a shallow copy and a deep copy?
Shallow copy is used when a new instance type gets created and it keeps values
that are copied whereas deep copy stores values that are already copied.
A shallow copy has faster program execution whereas a deep copy makes it slow.

29. Which sorting technique is used by sort() and sorted() functions of


python?
Python uses the Tim Sort algorithm for sorting. It’s a stable sorting whose worst
case is O(N log N). It’s a hybrid sorting algorithm, derived from merge sort and
insertion sort, designed to perform well on many kinds of real-world data.

30. What are Decorators?


Decorators are a very powerful and useful tool in Python as they are the specific
change that we make in Python syntax to alter functions easily.

31. How do you debug a Python program?


By using this command we can debug a Python program:
$ python -m pdb python-script.py

32. What are Iterators in Python?


In Python, iterators are used to iterate a group of elements, containers like a list.
Iterators are collections of items, and they can be a list, tuples, or a dictionary.
Python iterator implements __itr__ and the next() method to iterate the stored
elements. We generally use loops to iterate over the collections (list, tuple) in
Python.

33. What are Generators in Python?


In Python, the generator is a way that specifies how to implement iterators. It is a
normal function except that it yields expression in the function. It does not
implement __itr__ and next() method and reduces other overheads as well.
If a function contains at least a yield statement, it becomes a generator. The yield
keyword pauses the current execution by saving its states and then resumes from
the same when required.
34. Does Python supports multiple Inheritance?
Python does support multiple inheritances, unlike Java. Multiple inheritances
mean that a class can be derived from more than one parent class.

35. What is Polymorphism in Python?


Polymorphism means the ability to take multiple forms. So, for instance, if the
parent class has a method named ABC then the child class also can have a
method with the same name ABC having its own parameters and variables.
Python allows polymorphism.

36. Define encapsulation in Python?


Encapsulation means binding the code and the data together. A Python class is an
example of encapsulation.

37. How do you do data abstraction in Python?


Data Abstraction is providing only the required details and hides the
implementation from the world. It can be achieved in Python by using interfaces
and abstract classes.

38. How is memory management done in Python?


Python uses its private heap space to manage the memory. Basically, all the
objects and data structures are stored in the private heap space. Even the
programmer can not access this private space as the interpreter takes care of this
space. Python also has an inbuilt garbage collector, which recycles all the unused
memory and frees the memory and makes it available to the heap space.

39. How to delete a file using Python?


We can delete a file using Python by following approaches:
 os.remove()
 os.unlink()

40. What is slicing in Python?


Python Slicing is a string operation for extracting a part of the string, or some
part of a list. With this operator, one can specify where to start the slicing, where
to end, and specify the step. List slicing returns a new list from the existing list.
Syntax: Lst[ Initial : End : IndexJump ]

41. What is a namespace in Python?


A namespace is a naming system used to make sure that names are unique to
avoid naming conflicts.

Advanced Python Interview Questions & Answers

42. What is PIP?


PIP is an acronym for Python Installer Package which provides a seamless
interface to install various Python modules. It is a command-line tool that can
search for packages over the internet and install them without any user
interaction.

43. What is a zip function?


Python zip() function returns a zip object, which maps a similar index of multiple
containers. It takes an iterable, converts it into an iterator and aggregates the
elements based on iterables passed. It returns an iterator of tuples.

44. What are Pickling and Unpickling?


The Pickle module accepts any Python object and converts it into a string
representation and dumps it into a file by using the dump function, this process is
called pickling. While the process of retrieving original Python objects from the
stored string representation is called unpickling.

45. What is monkey patching in Python?


In Python, the term monkey patch only refers to dynamic modifications of a class
or module at run-time.
# g.py
class GeeksClass:
def function(self):
print "function()"

import m
def monkey_function(self):
print "monkey_function()"

m.GeeksClass.function = monkey_function
obj = m.GeeksClass()
obj.function()

46. What is __init__() in Python?


Equivalent to constructors in OOP terminology, __init__ is a reserved method in
Python classes. The __init__ method is called automatically whenever a new
object is initiated. This method allocates memory to the new object as soon as it
is created. This method can also be used to initialize variables.

47. Write a code to display the current time?


import time
currenttime= time.localtime(time.time())
print (“Current time is”, currenttime)

48. What are Access Specifiers in Python?


Python uses the ‘_’ symbol to determine the access control for a specific data
member or a member function of a class. A Class in Python has three types
of Python access modifiers :
 Public Access Modifier: The members of a class that are declared public are
easily accessible from any part of the program. All data members and member
functions of a class are public by default.
 Protected Access Modifier: The members of a class that are declared
protected are only accessible to a class derived from it. All data members of a
class are declared protected by adding a single underscore ‘_’ symbol before
the data members of that class.
 Private Access Modifier: The members of a class that are declared private
are accessible within the class only, the private access modifier is the most
secure access modifier. Data members of a class are declared private by
adding a double underscore ‘__’ symbol before the data member of that class.

49. What are unit tests in Python?


Unit Testing is the first level of software testing where the smallest testable parts
of the software are tested. This is used to validate that each unit of the software
performs as designed. The unit test framework is Python’s xUnit style
framework. The White Box Testing method is used for Unit testing.

50. Python Global Interpreter Lock (GIL)?


Python Global Interpreter Lock (GIL) is a type of process lock that is used by
Python whenever it deals with processes. Generally, Python only uses only one
thread to execute the set of written statements. The performance of the single-
threaded process and the multi-threaded process will be the same in Python and
this is because of GIL in Python. We cannot achieve multithreading in Python
because we have a global interpreter lock that restricts the threads and works as a
single thread.
51. What are Function Annotations in Python?
Function Annotation is a feature that allows you to add metadata to function
parameters and return values. This way you can specify the input type of the
function parameters and the return type of the value the function returns.
Function annotations are arbitrary Python expressions that are associated with
various parts of functions. These expressions are evaluated at compile time and
have no life in Python’s runtime environment. Python does not attach any
meaning to these annotations. They take life when interpreted by third-party
libraries, for example, mypy.

52. What are Exception Groups in Python?


The latest feature of Python 3.11, Exception Groups. The Exception Group can be
handled using a new except* syntax. The * symbol indicates that multiple
exceptions can be handled by each except* clause.
Exception Group is a collection/group of different kinds of Exception. Without
creating Multiple Exceptions we can group together different Exceptions which
we can later fetch one by one whenever necessary, the order in which the
Exceptions are stored in the Exception Group doesn’t matter while calling them.
Python
try:
raise ExceptionGroup('Example ExceptionGroup', (
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError'),
AttributeError('Example AttributeError')
))
except* TypeError:
...
except* ValueError as e:
...
except* (KeyError, AttributeError) as e:
...

53. What is Python Switch Statement


From version 3.10 upward, Python has implemented a switch case feature called
“structural pattern matching”. You can implement this feature with the match and
case keywords. Note that the underscore symbol is what you use to define a
default case for the switch statement in Python.

54. What is PEP 8 and why is it important?

PEP stands for Python Enhancement Proposal. A PEP is an official design


document providing information to the Python community, or describing a new
feature for Python or its processes. PEP 8 is especially important since it
documents the style guidelines for Python Code. Apparently contributing to the
Python open-source community requires you to follow these style guidelines
sincerely and strictly.

55. What is the difference between .py and .pyc files?

 .py files contain the source code of a program. Whereas, .pyc file contains the
bytecode of your program. We get bytecode after compilation of .py file (source
code). .pyc files are not created for all the files that you run. It is only created for
the files that you import.
 Before executing a python program python interpreter checks for the compiled
files. If the file is present, the virtual machine executes it. If not found, it checks
for .py file. If found, compiles it to .pyc file and then python virtual machine
executes it.
 Having .pyc file saves you the compilation time.

56. What is the use of help() and dir() functions?

help() function in Python is used to display the documentation of modules, classes,


functions, keywords, etc. If no parameter is passed to the help() function, then an
interactive help utility is launched on the console.
dir() function tries to return a valid list of attributes and methods of the object it is
called upon. It behaves differently with different objects, as it aims to produce the
most relevant data, rather than the complete information.

 For Modules/Library objects, it returns a list of all attributes, contained in that


module.
 For Class Objects, it returns a list of all valid attributes and base attributes.
 With no arguments passed, it returns a list of attributes in the current scope.

57. What is PYTHONPATH in Python?

PYTHONPATH is an environment variable which you can set to add additional


directories where Python will look for modules and packages. This is especially
useful in maintaining Python libraries that you do not wish to install in the global
default location.

58. What is walrus operator?


Walrus Operator allows you to assign a value to a variable within an
expression. This can be useful when you need to use a value multiple times
in a loop, but don’t want to repeat the calculation.
The Walrus Operator is represented by the := syntax and can be used in a
variety of contexts including while loops and if statements. The Assignment
expressions allow a value to be assigned to a variable, even a variable that
doesn’t exist yet, in the context of expression rather than as a stand-alone
statement.
Code :

numbers = [1, 2, 3, 4, 5]

while (n := len(numbers)) > 0:

print(numbers.pop())
oops
1. What is Object Oriented Programming (OOPs)?
Object Oriented Programming (also known as OOPs) is a programming
paradigm where the complete software operates as a bunch of objects
talking to each other. An object is a collection of data and the methods which
operate on that data.

2. Why OOPs?
The main advantage of OOP is better manageable code that covers the
following:
1. The overall understanding of the software is increased as the distance
between the language spoken by developers and that spoken by users.
2. Object orientation eases maintenance by the use of encapsulation. One
can easily change the underlying representation by keeping the methods
the same.
3. The OOPs paradigm is mainly useful for relatively big software.

3. What is a Class?
A class is a building block of Object Oriented Programs. It is a user-defined
data type that contains the data members and member functions that
operate on the data members. It is like a blueprint or template of objects
having common properties and methods.

4. What is an Object?
An object is an instance of a class. Data members and methods of a class
cannot be used directly. We need to create an object (or instance) of the
class to use them. In simple terms, they are the actual world entities that
have a state and behavior.

5. What are the main features of OOPs?


The main feature of the OOPs, also known as 4 pillars or basic principles of
OOPs are as follows:
1. Encapsulation
2. Data Abstraction
3. Polymorphism
4. Inheritance

6. What is Encapsulation?
Encapsulation is the binding of data and methods that manipulate them into
a single unit such that the sensitive data is hidden from the users
It is implemented as the processes mentioned below:
1. Data hiding: A language feature to restrict access to members of an
object. For example, private and protected members in C++.
2. Bundling of data and methods together: Data and methods that
operate on that data are bundled together. For example, the data
members and member methods that operate on them are wrapped into a
single unit known as a class.

7. What is Abstraction?
Abstraction is similar to data encapsulation and is very important in OOP. It
means showing only the necessary information and hiding the other
irrelevant information from the user. Abstraction is implemented using
classes and interfaces.

8. What is Polymorphism?
The word “Polymorphism” means having many forms. It is the property of
some code to behave differently for different contexts. For example, in C++
language, we can define multiple functions having the same name but
different working depending on the context.
Polymorphism can be classified into two types based on the time when the
call to the object or function is resolved. They are as follows:
 Compile Time Polymorphism
 Runtime Polymorphism
A) Compile-Time Polymorphism
Compile time polymorphism, also known as static polymorphism or early
binding is the type of polymorphism where the binding of the call to its code
is done at the compile time. Method overloading or operator overloading are
examples of compile-time polymorphism.
B) Runtime Polymorphism
Also known as dynamic polymorphism or late binding, runtime polymorphism
is the type of polymorphism where the actual implementation of the function
is determined during the runtime or execution. Method overriding is an
example of this method.
9. What is Inheritance? What is its purpose?
The idea of inheritance is simple, a class is derived from another class and
uses data and implementation of that other class. The class which is derived
is called child or derived or subclass and the class from which the child class
is derived is called parent or base or superclass.
The main purpose of Inheritance is to increase code reusability. It is also
used to achieve Runtime Polymorphism.

10. What are access specifiers? What is their significance in OOPs?


Access specifiers are special types of keywords that are used to specify or
control the accessibility of entities like classes, methods, and so
on. Private, Public, and Protected are examples of access specifiers or
access modifiers.
The key components of OOPs, encapsulation and data hiding, are largely
achieved because of these access specifiers.

11. What are the advantages and disadvantages of OOPs?


Advantages of OOPs Disadvantages of OOPs

The programmer should be well-skilled and


OOPs provides enhanced code should have excellent thinking in terms of
reusability. objects as everything is treated as an object
in OOPs.

The code is easier to maintain Proper planning is required because OOPs is


and update. a little bit tricky.

It provides better data security


OOPs concept is not suitable for all kinds of
by restricting data access and
problems.
avoiding unnecessary exposure.

Fast to implement and easy to


redesign resulting in minimizing The length of the programs is much larger in
the complexity of an overall comparison to the procedural approach.
program.
12. What other paradigms of programming exist besides OOPs?
The programming paradigm is referred to the technique or approach of
writing a program. The programming paradigms can be classified into the
following types:
It is a programming paradigm that works by changing the program state
through assignment statements. The main focus in this paradigm is on how
to achieve the goal. The following programming paradigms come under this
category:
1. Procedural Programming Paradigm: This programming paradigm is
based on the procedure call concept. Procedures, also known as routines
or functions are the basic building blocks of a program in this paradigm.
2. Object-Oriented Programming or OOP: In this paradigm, we visualize
every entity as an object and try to structure the program based on the
state and behavior of that object.
3. Parallel Programming: The parallel programming paradigm is the
processing of instructions by dividing them into multiple smaller parts and
executing them concurrently.
2. Declarative Programming Paradigm
Declarative programming focuses on what is to be executed rather than how
it should be executed. In this paradigm, we express the logic of a
computation without considering its control flow. The declarative paradigm
can be further classified into:
1. Logical Programming Paradigm: It is based on formal logic where the
program statements express the facts and rules about the problem in the
logical form.
2. Functional Programming Paradigm: Programs are created by applying
and composing functions in this paradigm.
3. Database Programming Paradigm: To manage data and information
organized as fields, records, and files, database programming models are
utilized.

13. What is the difference between Structured Programming and


Object Oriented Programming?
Structured Programming is a technique that is considered a precursor to
OOP and usually consists of well-structured and separated modules. It is a
subset of procedural programming. The difference between OOPs and
Structured Programming is as follows:
Object-Oriented Programming Structural Programming

A program’s logical structure is provided


Programming that is object-
by structural programming, which divides
oriented is built on objects having
programs into their corresponding
a state and behavior.
functions.

It follows a bottom-to-top
It follows a Top-to-Down approach.
approach.

Restricts the open flow of data to


No restriction to the flow of data. Anyone
authorized parts only providing
can access the data.
better data security.

Enhanced code reusability due to


Code reusability is achieved by using
the concepts of polymorphism and
functions and loops.
inheritance.

In this, methods are written


In this, the method works dynamically,
globally and code lines are
making calls as per the need of code for a
processed one by one i.e., Run
certain time.
sequentially.

Modifying and updating the code is Modifying the code is difficult as compared
easier. to OOPs.

Data is given more importance in


Code is given more importance.
OOPs.

14. What are some commonly used Object Oriented Programming


Languages?
OOPs paradigm is one of the most popular programming paradigms. It is
widely used in many popular programming languages such as:
 C++
 Java
 Python
 Javascript
 C#
 Ruby

15. What are the different types of Polymorphism?


Polymorphism can be classified into two types based on the time when the
call to the object or function is resolved. They are as follows:
1. Compile Time Polymorphism
2. Runtime Polymorphism
Compile time polymorphism, also known as static polymorphism or early
binding is the type of polymorphism where the binding of the call to its code
is done at the compile time. Method overloading or operator
overloading are examples of compile-time polymorphism.
Also known as dynamic polymorphism or late binding, runtime polymorphism
is the type of polymorphism where the actual implementation of the function
is determined during the runtime or execution. Method overriding is an
example of this method.

16. What is the difference between overloading and overriding?


A compile-time polymorphism feature called overloading allows an entity to
have numerous implementations of the same name. Method overloading and
operator overloading are two examples.
Overriding is a form of runtime polymorphism where an entity with the same
name but a different implementation is executed. It is implemented with the
help of virtual functions.

17. Are there any limitations on Inheritance?


Yes, there are more challenges when you have more authority. Although
inheritance is a very strong OOPs feature, it also has significant drawbacks.
 As it must pass through several classes to be implemented, inheritance
takes longer to process.
 The base class and the child class, which are both engaged in
inheritance, are also closely related to one another (called tightly
coupled). Therefore, if changes need to be made, they may need to be
made in both classes at the same time.
 Implementing inheritance might be difficult as well. Therefore, if not
implemented correctly, this could result in unforeseen mistakes or
inaccurate outputs.
18. What different types of inheritance are there?
Inheritance can be classified into 5 types which are as follows:
1. Single Inheritance: Child class derived directly from the base class
2. Multiple Inheritance: Child class derived from multiple base classes.
3. Multilevel Inheritance: Child class derived from the class which is also
derived from another base class.
4. Hierarchical Inheritance: Multiple child classes derived from a single
base class.
5. Hybrid Inheritance: Inheritance consisting of multiple inheritance types
of the above specified.
Note: Type of inheritance supported is dependent on the language. For
example, Java does not support multiple inheritance.

19. What is an interface?


A unique class type known as an interface contains methods but not their
definitions. Inside an interface, only method declaration is permitted. You
cannot make objects using an interface. Instead, you must put that interface
into use and specify the procedures for doing so.
20. How is an abstract class different from an interface?
Both abstract classes and interfaces are special types of classes that just
include the declaration of the methods, not their implementation. An abstract
class is completely distinct from an interface, though. Following are some
major differences between an abstract class and an interface.
Abstract Class Interface

A class that is abstract can have both An interface can only have
abstract and non-abstract methods. abstract methods.

An abstract class can have final, non-final, The interface has only static
static and non-static variables. and final variables.

Abstract class doesn’t support multiple An interface supports multiple


inheritance inheritance.
21. How much memory does a class occupy?
Classes do not use memory. They merely serve as a template from which
items are made. Now, objects actually initialize the class members and
methods when they are created, using memory in the process.

22. Is it always necessary to create objects from class?


No. If the base class includes non-static methods, an object must be
constructed. But no objects need to be generated if the class includes static
methods. In this instance, you can use the class name to directly call those
static methods.

23. What is the difference between a structure and a class in C++?


The structure is also a user-defined datatype in C++ similar to the class with
the following differences:
 The major difference between a structure and a class is that in a
structure, the members are set to public by default while in a class,
members are private by default.
 The other difference is that we use struct for declaring structure
and class for declaring a class in C++.

24. What is Constructor?


A constructor is a block of code that initializes the newly created object. A
constructor resembles an instance method but it’s not a method as it doesn’t
have a return type. It generally is the method having the same name as the
class but in some languages, it might differ. For example:
In python, a constructor is named __init__.
In C++ and Java, the constructor is named the same as the class name.

25. What are the various types of constructors?


The most common classification of constructors includes:
1. Default Constructor
2. Non-Parameterized Constructor
3. Parameterized Constructor
4. Copy Constructor
The default constructor is a constructor that doesn’t take any arguments. It is
a non-parameterized constructor that is automatically defined by the
compiler when no explicit constructor definition is provided.
It initializes the data members to their default values.
It is a user-defined constructor having no arguments or parameters.
The constructors that take some arguments are known as parameterized
constructors.
A copy constructor is a member function that initializes an object using
another object of the same class.
In Python, we do not have built-in copy constructors like Java and C++ but
we can make a workaround using different methods.

26. What is a destructor?


A destructor is a method that is automatically called when the object is made
of scope or destroyed.
In C++, the destructor name is also the same as the class name but with the
(~) tilde symbol as the prefix.
In Python, the destructor is named __del__.
In Java, the garbage collector automatically deletes the useless objects so
there is no concept of destructor in Java. We could have used finalize()
method as a workaround for the java destructor but it is also deprecated
since Java 9.

27. Can we overload the constructor in a class?


Yes We can overload the constructor in a class in Java. Constructor
Overloading is done when we want constructor with different constructor with
different parameter(Number and Type).

28. Can we overload the destructor in a class?


No, a destructor cannot be overloaded in a class. The can only be one
destructor present in a class.

29. What is the virtual function?


A virtual function is a function that is used to override a method of the parent
class in the derived class. It is used to provide abstraction in a class.
In C++, a virtual function is declared using the virtual keyword,
In Java, every public, non-static, and non-final method is a virtual function.
Python methods are always virtual.

30. What is pure virtual function?


A pure virtual function, also known as an abstract function is a member
function that doesn’t contain any statements. This function is defined in the
derived class if needed.

You might also like