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

python QB unit 4

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, inheritance, polymorphism, encapsulation, and data abstraction. It explains the creation of classes and objects, types of inheritance, and constructors, along with examples for better understanding. Additionally, it covers data hiding and the different types of polymorphism, highlighting their significance in programming.

Uploaded by

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

python QB unit 4

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, inheritance, polymorphism, encapsulation, and data abstraction. It explains the creation of classes and objects, types of inheritance, and constructors, along with examples for better understanding. Additionally, it covers data hiding and the different types of polymorphism, highlighting their significance in programming.

Uploaded by

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

Unit IV Question bank

Q1.) Explain OOP’s Concept in Python

Ans: OOPs Concepts in Python


 Class in Python
 Objects in Python
 Polymorphism in Python
 Encapsulation in Python
 Inheritance in Python
 Data Abstraction in Python

Class:
A class is a collection of objects. Classes are blueprints for creating objects. A class defines a
set of attributes and methods that the created objects (instances) can have.

Creating a Class :
class Dog:

species = "Canine" # Class attribute

def __init__(self, name, age):

self.name = name # Instance attribute

self.age = age # Instance attribute

Objects
An Object is an instance of a Class. It represents a specific implementation of the class and holds
its own data.
An object consists of:
 State: It is represented by the attributes and reflects the properties of an object.
 Behavior: It is represented by the methods of an object and reflects the response of an
object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other
objects.

Creating Object :
class Dog:

species = "Canine" # Class attribute

def __init__(self, name, age):


self.name = name # Instance attribute

self.age = age # Instance attribute

# Creating an object of the Dog class

dog1 = Dog("Buddy", 3)

print(dog1.name)

print(dog1.species)

Output:
Buddy
Canine

Explanation:
 dog1 = Dog(“Buddy”, 3): Creates an object of the Dog class with name as “Buddy” and
age as 3.
 dog1.name: Accesses the instance attribute name of the dog1 object.
 dog1.species: Accesses the class attribute species of the dog1 object.

Inheritance
Inheritance allows a class (child class) to acquire properties and methods of another class
(parent class). It supports hierarchical classification and promotes code reuse.

Types of Inheritance:
1. Single Inheritance: A child class inherits from a single parent class.
2. Multiple Inheritance: A child class inherits from more than one parent class.
3. Multilevel Inheritance: A child class inherits from a parent class, which in turn inherits
from another class.
4. Hierarchical Inheritance: Multiple child classes inherit from a single parent class.
5. Hybrid Inheritance: A combination of two or more types of inheritance.

Polymorphism
Polymorphism allows methods to have the same name but behave differently based on the
object’s context. It can be achieved through method overriding or overloading.
Types of Polymorphism
1. Compile-Time Polymorphism: This type of polymorphism is determined during the
compilation of the program. It allows methods or operators with the same name to behave
differently based on their input parameters or usage. It is commonly referred to as method
or operator overloading.
2. Run-Time Polymorphism: This type of polymorphism is determined during the execution
of the program. It occurs when a subclass provides a specific implementation for a method
already defined in its parent class, commonly known as method overriding.

Encapsulation:
Encapsulation is the bundling of data (attributes) and methods (functions) within a class,
restricting access to some components to control interactions.
A class is an example of encapsulation as it encapsulates all the data that is member functions,
variables, etc.

Types of Encapsulation:
1. Public Members: Accessible from anywhere.
2. Protected Members: Accessible within the class and its subclasses.
3. Private Members: Accessible only within the class.

Data Abstraction
Abstraction hides the internal implementation details while exposing only the necessary
functionality. It helps focus on “what to do” rather than “how to do it.”
Types of Abstraction:
 Partial Abstraction: Abstract class contains both abstract and concrete methods.
 Full Abstraction: Abstract class contains only abstract methods (like interfaces).

Q2.) Describe Constructors in python


Ans: In Python, a constructor is a special method that is called automatically when an object is
created from a class. Its main role is to initialize the object by setting up its attributes or state.
Types of Constructors
Constructors can be of two types.
1. Default Constructor
A default constructor does not take any parameters other than self. It initializes the object
with default attribute values.

class Car:
def __init__(self):

#Initialize the Car with default attributes


self.make = "Toyota"
self.model = "Corolla"
self.year = 2020

# Creating an instance using the default constructor


car = Car()
print(car.make)
print(car.model)
print(car.year)

Output
Toyota
Corolla
2020

Parameterized Constructor:
A parameterized constructor accepts arguments to initialize the object’s attributes with
specific values.

class Car:
def __init__(self, make, model, year):

#Initialize the Car with specific attributes.


self.make = make
self.model = model
self.year = year

# Creating an instance using the parameterized constructor


car = Car("Honda", "Civic", 2022)
print(car.make)
print(car.model)
print(car.year)

Output
Honda
Civic
2022

Q3.Explain polymorphism in python with example


Ans: Polymorphism is a foundational concept in programming that allows entities like
functions, methods or operators to behave differently based on the type of data they are
handling. Derived from Greek, the term literally means “many forms”.
Python’s dynamic typing and duck typing make it inherently polymorphic. Functions,
operators and even built-in objects like loops exhibit polymorphic behavior.

Example:
print(len("Hello")) # String length
print(len([1, 2, 3])) # List length

print(max(1, 3, 2)) # Maximum of integers


print(max("a", "z", "m")) # Maximum in strings

Types of Polymorphism
Compile-time Polymorphism
 Found in statically typed languages like Java or C++, where the behavior of a function or
operator is resolved during the program’s compilation phase.
 Examples include method overloading and operator overloading, where multiple functions
or operators can share the same name but perform different tasks based on the context.
 In Python, which is dynamically typed, compile-time polymorphism is not natively
supported. Instead, Python uses techniques like dynamic typing and duck typing to achieve
similar flexibility.
Runtime Polymorphism
 Occurs when the behavior of a method is determined at runtime based on the type of the
object.
 In Python, this is achieved through method overriding: a child class can redefine a method
from its parent class to provide its own specific implementation.
 Python’s dynamic nature allows it to excel at runtime polymorphism, enabling flexible and
adaptable code.

Q4. What is data hiding in python

Ans: Data hiding in python is a technique of preventing methods and variables of a class from
being accessed directly outside of the class in which the methods and variables are initialized. Data
hiding of essential member function prevents the end user from viewing the implementation of the
program hence increasing security. The use of data hiding also helps in reducing the complexity
of the program by reducing interdependencies.
Data hiding in python can be achieved by declaring class members as private by putting a double
underscore (__) as prefix before the member name.

Syntax

The syntax for hiding data in python is as follows :

__variablename

Example:

class Employee:

# Hidden members of the class

__password = 'private12345' # Private member

_id = '12345' # Protected member

def Details(self):

print("ID: ",(self._id))
print("Password: ",(self.__password)+"\n")

hidden = Employee()

hidden.Details()

print(hidden._Employee__password)

Output

The output of the above code is :

ID: 12345

Password: private12345

private12345

Q5.Explain Single Inheritance in Python


Ans: Single Inheritance:
Single inheritance enables a derived class to inherit properties from a single parent class, thus
enabling code reusability and the addition of new features to existing code.

Example:
# 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.

Q6. Explain multilevel inheritance with example


Ans:
Multilevel Inheritance :
In multilevel inheritance, features of the base class and the derived class are further inherited
into the new derived class. This is similar to a relationship representing a child and a
grandfather

.
Example:

# Python program to demonstrate

# multilevel inheritance

# Base class

class Grandfather:

def __init__(self, grandfathername):

self.grandfathername = grandfathername

# Intermediate class

class Father(Grandfather):

def __init__(self, fathername, grandfathername):


self.fathername = fathername

# invoking constructor of Grandfather class

Grandfather.__init__(self, grandfathername)

# Derived class

class Son(Father):

def __init__(self, sonname, fathername, grandfathername):

self.sonname = sonname

# invoking constructor of Father class

Father.__init__(self, fathername, grandfathername)

def print_name(self):

print('Grandfather name :', self.grandfathername)

print("Father name :", self.fathername)

print("Son name :", self.sonname)

# Driver code

s1 = Son('Ajay', 'Rampal', 'Sharma')


print(s1.grandfathername)

s1.print_name()

output:
Lal mani
Grandfather name : Sharma
Father name : Rampal
Son name : Ajay
Q7.Explain multiple inheritance with example
Ans: Multiple Inheritance:
When a class can be derived from more than one base class this type of inheritance is called
multiple inheritances. In multiple inheritances, all the features of the base classes are inherited
into the derived class.

Example:

# Python program to demonstrate

# multiple inheritance

# Base class1

class Mother:

mothername = ""
def mother(self):

print(self.mothername)

# Base class2

class Father:

fathername = ""

def father(self):

print(self.fathername)

# Derived class

class Son(Mother, Father):

def parents(self):

print("Father :", self.fathername)

print("Mother :", self.mothername)

# Driver's code

s1 = Son()
s1.fathername = "RAM"

s1.mothername = "SITA"

s1.parents()

Output:
Father : RAM
Mother : SITA

You might also like