[go: up one dir, main page]

0% found this document useful (0 votes)
5 views19 pages

Pip 5

The document outlines the academic curriculum for the Computer Engineering Department at Bhivrabai Sawant Polytechnic for the 2024-25 academic year, focusing on Object-Oriented Programming (OOP) concepts in Python. It includes a series of questions and answers related to OOP principles, such as inheritance, encapsulation, and method resolution order, along with examples and explanations. The document serves as a guide for students to understand key programming concepts and their applications in Python.

Uploaded by

saloni.tanmor1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

Pip 5

The document outlines the academic curriculum for the Computer Engineering Department at Bhivrabai Sawant Polytechnic for the 2024-25 academic year, focusing on Object-Oriented Programming (OOP) concepts in Python. It includes a series of questions and answers related to OOP principles, such as inheritance, encapsulation, and method resolution order, along with examples and explanations. The document serves as a guide for students to understand key programming concepts and their applications in Python.

Uploaded by

saloni.tanmor1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

JAYAWANT SHIKSHAN PRASARAK MANDAL’s

Bhivrabai Sawant Polytechnic


(Approved by AICTE, New Delhi, Govt. of Maharashtra, Affiliated to MSBTE Mumbai)
Gat No. 720 (1&2), Wagholi, Pune-Nagar Road, Pune-412207)
Phone: 020 – 65335100 Tele fax: - + 91-020-65335100
E-mail: bspoly@rediffmail.com Website: www.jspm.edu.in

Computer Engineering Department


Academic Year 2024-25
PIP Questions on Chapter 5
Course: Programming with Python Course Code: 22616
Que.N Bloom’s Marks Assignment Questions
o. Level
1 1,2 2 What is Object-Oriented Programming (OOP) in Python? Explain its advantages.
2 4 6 What is Object-Oriented Programming (OOP)? Explain its key features.

3 2 4 What is the Difference Between self and cls in Python?


4 1,2 2 What is Inheritance in OOP? Explain its types with examples.

5 2 4 What is a static method in Python? How is it different from an instance method?


6 2 4 What is Method Resolution Order (MRO) in Python?

7 2 4 What is an Abstract Class in Python? Explain with an example

8 2 4 Discuss the role of encapsulation in data security with an example


9 1,2 2 What is the difference between a class and an object?

10 1,2 2 What is method overloading in Python? Does Python support it?


11 1,2 2 What is a constructor in Python? How is it defined?
12 1,2 2 Explain the concept of Encapsulation with an example in Python.

Sign of Course Coordinator Sign of Module Coordinator Sign of H.O.


JAYAWANT SHIKSHAN PRASARAK MANDAL’s

Bhivrabai Sawant Polytechnic


(Approved by AICTE, New Delhi, Govt. of Maharashtra, Affiliated to MSBTE Mumbai)
Gat No. 720 (1&2), Wagholi, Pune-Nagar Road, Pune-412207)
Phone: 020 – 65335100 Tele fax: - + 91-020-65335100
E-mail: bspoly@rediffmail.com Website: www.jspm.edu.in

Computer Engineering Department


Academic Year 2024-25
PIP Chapter 4 Solution
Course: Programming with Python Course Code: 22616

Que.N Bloom’s
Marks Assignment Questions
o. Level
1 1, 2 4 What is Object-Oriented Programming (OOP) in Python? Explain its advantages.
Marking Scheme 2 marks deftn, 2 marks advantages
Object-Oriented Programming (OOP) is a programming paradigm in Python that is
based on the concept of objects and classes. It allows the organization of code into
reusable and modular components by grouping data and behavior together.
A class is a blueprint for creating objects, and an object is an instance of a class that
holds data (attributes) and functions (methods).
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def display_info(self):
return f"Car: {self.brand} {self.model}"

Answer # Creating an object of the class Car


car1 = Car("Toyota", "Corolla")
print(car1.display_info()) # Output: Car: Toyota Corolla
Advantages of OOP in Python:
1. Code Reusability – OOP allows the reuse of existing code through inheritance,
reducing redundancy and development time.
2. Encapsulation (Data Security) – Data is protected using private and protected
access modifiers, preventing unintended modifications.
3. Modularity & Maintainability – The code is structured into self-contained
objects, making it easier to maintain and debug.
4. Polymorphism (Flexibility) – A single function can work with different types
of objects, enhancing flexibility and reducing code duplication.
5. Scalability – Large projects can be efficiently managed using OOP principles,
allowing easy expansion and modification.
Overall, OOP in Python makes programming more efficient, organized, and scalable,
making it a preferred choice for software development.

2 1,2 6 What is Object-Oriented Programming (OOP)? Explain its key features.

Marking Scheme definition 2M, feature 2m, 2m explain


Object-Oriented Programming (OOP) is a programming paradigm that focuses on
organizing code using objects and classes rather than relying on functions and
procedures. It is widely used in modern programming languages like Python, Java,
and C++.
• A class is a blueprint for creating objects. It defines properties (attributes) and
behaviors (methods).
• An object is an instance of a class that holds specific values for the attributes
and can perform actions using the methods defined in the class.
Example of OOP in Python:
python
CopyEdit
class Student:
def __init__(self, name, age):
self.name = name # Attribute
self.age = age # Attribute

Answer def display(self): # Method


return f"Student Name: {self.name}, Age: {self.age}"

# Creating an object
student1 = Student("John", 20)
print(student1.display()) # Output: Student Name: John, Age: 20
Here, Student is a class, and student1 is an object created from that class.

Key Features of OOP


1. Encapsulation (Data Hiding and Protection)
Encapsulation is the concept of binding data and methods together within a class
while restricting direct access to the data from outside. This prevents accidental
modification of critical data and enhances security.
In Python, encapsulation is achieved using private variables (prefixing with __).
Example:
python
CopyEdit
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable

def deposit(self, amount):


self.__balance += amount

def withdraw(self, amount):


if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds")

def get_balance(self):
return self.__balance # Accessing private variable via method

# Creating an account
account = BankAccount(5000)
print(account.get_balance()) # Allowed: Output - 5000
print(account.__balance) # Error: Cannot access private attribute directly
🔹 Here, the balance is a private attribute, and it cannot be accessed directly,
ensuring data security.

2. Abstraction (Hiding Implementation Details)


Abstraction hides complex implementation details and only exposes necessary
functionalities to the user. This improves code readability and usability.
In Python, abstract classes (using ABC module) are used to enforce abstraction by
requiring subclasses to implement specific methods.
Example:
python
CopyEdit
from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass # Abstract method

class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.14 * self.radius * self.radius # Must implement area()

circle = Circle(5)
print(circle.area()) # Output: 78.5
🔹 The Shape class cannot be instantiated, and all subclasses must implement the
area() method.

3. Inheritance (Code Reusability)


Inheritance allows a new class (child class) to inherit properties and behaviors from
an existing class (parent class). This promotes code reusability and reduces
redundancy.
Types of Inheritance in Python:
1. Single Inheritance – One child inherits from a single parent.
2. Multiple Inheritance – A child class inherits from multiple parent classes.
3. Multilevel Inheritance – A class inherits from another child class.
4. Hierarchical Inheritance – Multiple child classes inherit from the same
parent.
5. Hybrid Inheritance – A combination of multiple types of inheritance.
Example of Single Inheritance:
python
CopyEdit
class Animal:
def speak(self):
return "Animal makes a sound"

class Dog(Animal): # Inheriting from Animal


def speak(self):
return "Dog barks"

dog = Dog()
print(dog.speak()) # Output: Dog barks
🔹 The Dog class inherits the speak() method from the Animal class and modifies it.

4. Polymorphism (One Interface, Many Implementations)


Polymorphism allows different classes to respond to the same function or method
call in different ways. It provides flexibility in writing generic code.
Types of Polymorphism:
1. Method Overriding – A child class redefines a method from the parent class.
2. Method Overloading – A function behaves differently based on the
number/type of arguments. (Python does not support overloading directly.)
Example of Method Overriding:
python
CopyEdit
class Vehicle:
def move(self):
return "Vehicle moves"

class Car(Vehicle):
def move(self):
return "Car drives on the road"

class Boat(Vehicle):
def move(self):
return "Boat sails on water"

car = Car()
boat = Boat()

print(car.move()) # Output: Car drives on the road


print(boat.move()) # Output: Boat sails on water
🔹 Here, Car and Boat override the move() method, showing different behavior.

5. Classes and Objects (Core Building Blocks)


• A class is a blueprint that defines attributes and methods.
• An object is an instance of a class with its own values.
Example:
python
CopyEdit
class Laptop:
def __init__(self, brand, price):
self.brand = brand
self.price = price

def show_details(self):
return f"Laptop: {self.brand}, Price: {self.price}"

laptop1 = Laptop("Dell", 60000)


print(laptop1.show_details()) # Output: Laptop: Dell, Price: 60000
🔹 Here, Laptop is a class, and laptop1 is an object storing details.
Conclusion:
Object-Oriented Programming (OOP) is a powerful approach to software design that
helps in writing modular, reusable, and maintainable code. Python supports all key
OOP principles, making it an excellent language for object-oriented development

3 2,4 4 What is the difference between self and cls in Python?


Marking Scheme 2M each topic 4 point
In Python, both self and cls are conventional naming conventions used in object-
oriented programming (OOP). They are commonly seen in instance methods and
class methods, respectively.
Although they serve different purposes, both self and cls act as placeholders for an
instance or class reference when defining methods within a class.
1. self – Instance Reference
self is a reference to the current instance of a class. It allows instance methods to
access instance-specific data and attributes.
• It is always the first parameter in an instance method but is passed
automatically by Python.
• It is not a keyword, but a widely accepted convention.
• It is used to modify or retrieve instance attributes inside the class.
Answer 2. cls – Class Reference
cls is used in class methods, which operate on the class level rather than on instance
objects. It refers to the class itself, not an individual instance.
• It is used as the first parameter in class methods.
• It allows modifying class attributes, which are shared among all instances.
• It is used with the @classmethod decorator.

Featu self (Instance cls (Class


re Method) Method)

Scop Refers to the specific instance of Refers to the class


e a class itself

Use Access or modify instance Modify or access class


Case attributes attributes
Method Used in instance Used in class methods
Type methods (@classmethod)

Applies Only to the calling Affects the whole class and all
To instance instances

Decorator No decorator Requires


Required? required @classmethod
4 1,2 2 What is Inheritance in OOP? Explain its types with examples.
Marking Scheme 1M defintn, 1mtypes

Inheritance is a key concept in OOP that allows a child class to inherit properties and methods
from a parent class. This promotes code reusability and reduces redundancy.
Types of Inheritance in Python:
1. Single Inheritance – One child class inherits from a single parent class.
Answer
2. Multiple Inheritance – A child class inherits from multiple parent classes.
3. Multilevel Inheritance – A child class inherits from another child class, forming a chain.
4. Hierarchical Inheritance – Multiple child classes inherit from a single parent class.
5. Hybrid Inheritance – A combination of different types of inheritance.

5 2 4 What is a static method in Python? How is it different from an instance method?


Marking Scheme defntn 2M , points 2M
Static Method:
A static method in Python is a method that belongs to a class but does not access
instance (self) or class (cls) attributes. It behaves like a regular function but is
included inside a class for logical grouping.
• Defined using the @staticmethod decorator.
• Cannot modify object (self) or class (cls) attributes.
• Used for utility functions that are related to the class but do not require instance
or class-level data.
Answer
Feature Static Method (@staticmethod) Instance Method (self)
Access to self? No Yes
Access to cls? No Yes
Purpose Utility function related to class Works with instance attributes
Decorator Used? @staticmethod No decorator required
Example Utility methods (e.g., calculations) Instance-specific behaviors

6 2 4 What is Method Resolution Order (MRO) in Python?.


Marking Scheme
Definition:
Method Resolution Order (MRO) in Python defines the sequence in which a class's
methods and attributes are searched when called. It plays a crucial role in multiple
inheritance, ensuring that Python resolves method calls in a consistent and
predictable order.
MRO follows the C3 linearization (also called C3 superclass linearization or the C3
algorithm), which ensures:
Depth-First Search (DFS): Methods are looked up in the first parent before moving
to other parents.
Answer
Left-to-Right Order: The order in which parent classes are inherited matters.
No Repeated Parent Calls: A parent class is not searched multiple times.

MRO determines the order of method resolution in Python classes.


Python follows the C3 linearization algorithm for consistency.
We can check MRO using __mro__ or mro().
In multiple inheritance, the first parent is given priority.

7 4 4 What is an Abstract Class in Python? Explain with an example

Marking Scheme Definition 2M, example 2M


Definition:
An abstract class in Python is a class that cannot be instantiated directly and is meant to be inherited by
subclasses. It serves as a blueprint for other classes by defining abstract methods that must be
implemented by child classes.
Abstract classes are defined using the ABC (Abstract Base Class) module from the abc library.
• It may contain both abstract and concrete methods.
• It ensures that all child classes implement the required methods.
• If a subclass does not implement the abstract method, Python will raise an error.
How to Define an Abstract Class?
To create an abstract class, we:
1. Import ABC and abstractmethod from the abc module.
2. Inherit from ABC.
3. Define at least one abstract method using @abstractmethod.
from abc import ABC, abstractmethod

Answer # Abstract Class


class Animal(ABC):

@abstractmethod
def make_sound(self): # Abstract method
pass

def sleep(self): # Concrete method


return "Sleeping..."

# Subclass 1 - Implements the abstract method


class Dog(Animal):
def make_sound(self):
return "Bark!"

# Subclass 2 - Implements the abstract method


class Cat(Animal):
def make_sound(self):
return "Meow!"

# Creating objects
dog = Dog()
cat = Cat()

print(dog.make_sound()) # Output: Bark!


print(cat.make_sound()) # Output: Meow!
print(dog.sleep()) # Output: Sleeping...
Animal is an abstract class containing:
• make_sound() → an abstract method (must be implemented in subclasses).
• sleep() → a concrete method (inherited by subclasses).
Dog and Cat inherit Animal and implement make_sound(), ensuring they are valid subclasses.
We can create objects of Dog and Cat, but not of Animal, ensuring abstraction.

8 2 4 Discuss the role of encapsulation in data security with an example


Marking Scheme Explain 2M , ex. 2M
Role of Encapsulation in Data Security
Encapsulation is an OOP principle that protects data by restricting direct access and
allowing controlled modifications through methods. It helps in securing sensitive
information by using private variables (__variable) and providing access via getter
and setter methods.
class BankAccount:
def __init__(self, holder, balance):
self.holder = holder
self.__balance = balance

def get_balance(self):
return f"Balance: ₹{self.__balance}"

def deposit(self, amount):


if amount > 0:
self.__balance += amount
Answer
return f"₹{amount} deposited."
return "Invalid deposit."

def withdraw(self, amount):


if 0 < amount <= self.__balance:
self.__balance -= amount
return f"₹{amount} withdrawn."
return "Insufficient balance."

account = BankAccount("Gouri", 5000)


print(account.get_balance()) # Balance: ₹5000

Prevents Direct Modification – __balance cannot be changed directly.


Ensures Data Integrity – Only valid transactions are allowed.
Controlled Access – Data is accessed securely through methods.

9 2 4 What is the difference between a class and an object?


Marking Scheme
2M for each topic
Class:
A class is a blueprint or template for creating objects. It defines the attributes
(variables) and behaviors (methods) that objects of that class will have. A class
itself does not store data; it only provides a structure that objects will follow.
For example, if we consider a Car as a class, it defines properties like color,
model, and engine type but does not represent an actual car.
Object:
An object is an instance of a class. It is a real-world entity that has specific values
assigned to its attributes. Each object created from a class has its own identity and
stores data independently.
For example, if we create an object car1 from the Car class, it may have specific
values like Red color and Tesla model.
Class object
Answer Defi
A template or blueprint for An instance of a class with
nitio
creating objects. actual values.
n
Memor Does not occupy memory until an Occupies memory when
y Usage object is created. instantiated.
Pu
rp Defines attributes (variables) Represents a real-world entity
os and behaviors (methods). with defined properties.
e
Ex A Car class defines
car1 = Car("Red", "Tesla") is an
am attributes like color and
object with specific values.
ple model.

10 4 2 What is method overloading in Python? Does Python support it?.


Method Overloading in Python
Method Overloading is a concept in Object-Oriented Programming where multiple
methods in the same class share the same name but have different parameters. It
allows different ways to call the same method based on the number or type of
arguments passed.

Does Python Support Method Overloading?


Unlike other languages like Java or C++, Python does not support method
overloading directly because it allows only the latest defined method with the same
Answer name to be used. However, we can achieve similar functionality using default
arguments or the *args and **kwargs parameters

class Calculator:
def add(self, a, b=0, c=0): # Default parameters allow overloading behavior
return a + b + c

calc = Calculator()
print(calc.add(5)) # Output: 5
print(calc.add(5, 10)) # Output: 15
print(calc.add(5, 10, 15)) # Output: 30

11 What is a constructor in Python? How is it defined?

A constructor is a special method in Python that is automatically called when an object


of a class is created. It is used to initialize the object's attributes.

How is a Constructor Defined?


answer In Python, a constructor is defined using the __init__() method inside a class.

The constructor method is always named __init__().


It initializes object attributes when an object is created.
It is automatically called without explicit invocation. 🚀
Explain the concept of Encapsulation with an example in Python.
12

Encapsulation is a mechanism in OOP that binds data and methods that manipulate
the data into a single unit. It restricts direct access to some of an object’s components,
making the data secure.
In Python, encapsulation is achieved using private variables (prefixing variable names
with __).

class BankAccount:
def __init__(self, account_holder, balance):
self.account_holder = account_holder # Public attribute
self.__balance = balance # Private attribute

def deposit(self, amount):


self.__balance += amount
answer

def withdraw(self, amount):


if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient balance")

def get_balance(self):
return self.__balance # Accessing private variable through a method

# Creating an object
account = BankAccount("John", 5000)
print(account.get_balance()) # Accessing balance via method
print(account.__balance) # This will raise an AttributeError

You might also like