Important Question Mad

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

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 2022-23
PIP-Chapter 5
Course: Programming with python               Course Code: 22616                
Semester: VI  

Que. Bloom’s Marks Questions Relevance to


No. Level CO 
1 2 2 Define class? How to create a class and its object in
python.
2 2 2 State the use of parameter “self” in python class.’

3 1 2 Differentiate between method overloading and method


overriding.
4 1 2 Explain the use __str__() and __repr__() function in
python.
5 3 2 Explain Destructor in python.
6 2 2 Explain constructor function in python class with
example.
7 1 2 Describe Data Hiding.
Write a program to demonstrate parameterized
8 1 4 COI 602.5
constructor in base class and derived class
Write a program to demonstrate constructor with default
9 3 4
arguments.
10 2 4 Write a program to create a python class and delete
objects of that class using del keyword.
11 2 4 Explain inheritance in python with examples.
12 2 4 Create a class employee with data members: name,
department and salary. Create suitable methods for
reading and printing employee information.
13 3 4 Explain data abstraction in detail.

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


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 2022-23
PIP-Chapter 5(solution)
Course: Programming with python Course Code: 22616            Semester: VI  

Que. Bloom Mark Questions Relevance


No. ’s s to CO 
Level
1 2 2 Define class? How to create a class and its object in python.
ANSWER ● In object-oriented programming, a class is a blueprint or a
template
● for creating objects that have similar properties and behaviors.
It specifies the attributes and methods that an object will have,
but does not create the object itself.

Here is an example of creating a simple class in Python:

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

def say_hello(self): COI 602.5


print(f"Hello, my name is {self.name} and I am {self.age} years
old.")

To create an object from this class, we can use the following code:

person1 = Person("Alice", 25)


person2 = Person("Bob", 30)

We can then call the `say_hello` method on these objects to print out a
message:

person1.say_hello() # Output: Hello, my name is Alice and I am 25


years old.
person2.say_hello() # Output: Hello, my name is Bob and I am 30
years old.
This will output a message with the name and age of each person
object.

2 2 2 State the use of parameter “self” in python class.’


ANSWER ● In Python, `self` is a reference to the current instance of a class.
It is used as the first parameter in the method definition of a
class, and it refers to the object that the method is being called
on.
● When a method is called on an object, Python automatically
passes the reference to that object as the first argument to the
method, which is typically named `self`. This allows the method
to access the attributes and methods of the object that it is called
on.

For example, let's consider the following class:

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

def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age}
years old.")

● In the `__init__` method, `self` refers to the newly created


instance of the `Person` class. The `self.name` and `self.age`
attributes are specific to that instance of the class.
● Similarly, in the `say_hello` method, `self` refers to the instance
of the `Person` class that the method is being called on. This
allows the method to access the `name` and `age` attributes of
the object using `self.name` and `self.age`, respectively.

3 1 2 Differentiate between method overloading and method overriding.
ANSWER

4 1 4 Explain the use __str__() and __repr__() function in python.


ANSWER
__repr__():

● __repr__() is a special method used to provide a string


representation of an object that can be used to recreate
that object.
● This function is called by the built-in repr() function and
is intended to provide a detailed and unambiguous
representation of the object.
● By default, if a class does not have a __repr__() method,
Python will use the default implementation, which returns
a string in the format <classname object at
memory_address>.
● Example

class MyClass:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"MyClass({self.value})"

● In this example, the MyClass class defines a __repr__()


method that returns a string representation of the object
in the format MyClass(value). This representation can be
used to recreate the object by passing the string to the
eval() function.
__str__():

● __str__() is a special method used to provide a string


representation of an object that is intended for human
consumption.
● This function is called by the built-in str() function and is
intended to provide a more readable and user-friendly
representation of the object.
● By default, if a class does not have a __str__() method,
Python will use the __repr__() method as a fallback.
● Example

class MyClass:
def __init__(self, value):
self.value = value

def __str__(self):
return f"MyClass object with value {self.value}

● In this example, the MyClass class defines a __str__()


method that returns a string representation of the object
in a human-readable format. This representation can be
used in print statements and other contexts where a
human-readable string is required.

5 3 2 Explain Destructor in python.


ANSWER ● In Python, a destructor is a special method called __del__() that
is called when an object is about to be destroyed. The destructor
is used to perform any final cleanup tasks that need to be done
before the object is deleted.
● The __del__() method is called automatically when an object is
about to be destroyed and cannot be called manually.
● class MyClass:
def __init__(self):
print("Creating object")

def __del__(self):
print("Destroying object")

● In this example, the MyClass class defines a __del__() method


that prints a message when the object is being destroyed. When
an instance of the class is created, the __init__() method is
called and prints a message, and when the instance is destroyed,
the __del__() method is called and prints a message.
● A destructor is a useful tool for performing final cleanup tasks
when an object is being destroyed, but it should be used with
caution and only when necessary.

6 2 2 Explain constructor function in python class with example.


ANSWER ● In Python, a constructor is a special method called `__init__()` that is
called when an object is created from a class. The constructor is used
to initialize the state of an object by setting its attributes to default or
user-defined values.

Here's an example of how to define a constructor for a class:

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

def print_info(self):
print(f"Name: {self.name}, Age: {self.age}")

● In this example, the `MyClass` class defines a constructor method


that takes two parameters, `name` and `age`, and sets the
corresponding attributes of the object. The class also defines a
`print_info()` method that prints the name and age of the object.

To create an instance of the class and call its methods, you can do the
following:

obj = MyClass("John", 25)


obj.print_info() # Output: Name: John, Age: 25

● In this example, a new instance of the `MyClass` class is created with


the name "John" and age 25. The `print_info()` method is then called
on the object, which prints its name and age.

● Overall, the constructor is a useful tool for initializing the state of an


object when it is created. By defining a constructor method in your
class, you can ensure that your objects are always initialized with the
correct values.

7 1 2 Describe Data Hiding.


● In object-oriented programming, data hiding is the concept of making
certain attributes or methods of a class inaccessible to users of the
class. This is done by using access modifiers such as public, private,
and protected, which control the visibility of class members.
ANSWER
● In Python, data hiding is achieved by using the convention of using
underscores to indicate the visibility of an attribute or method.
Specifically, attributes and methods that are prefixed with a single
underscore (e.g., `_attr`) are considered "protected" and should not be
accessed directly from outside the class, although they can be
accessed if needed. Attributes and methods that are prefixed with two
underscores (e.g., `__attr`) are considered "private" and are
completely inaccessible from outside the class.

Here's an example of how to use data hiding in Python:

```python
class MyClass:
def __init__(self):
self.public_attr = "This is a public attribute"
self._protected_attr = "This is a protected attribute"
self.__private_attr = "This is a private attribute"

def public_method(self):
print("This is a public method")

def _protected_method(self):
print("This is a protected method")

def __private_method(self):
print("This is a private method")

obj = MyClass()

# Accessing public attributes and methods


print(obj.public_attr) # Output: This is a public attribute
obj.public_method() # Output: This is a public method

# Accessing protected attributes and methods


print(obj._protected_attr) # Output: This is a protected attribute
obj._protected_method() # Output: This is a protected method

# Accessing private attributes and methods


# This will raise an AttributeError because the attribute is private
print(obj.__private_attr)
# This will also raise an AttributeError because the method is private
obj.__private_method()
```

● When creating an instance of the class, you can access the public
attributes and methods directly using dot notation.
● The protected attributes and methods can also be accessed directly,
but it is recommended to treat them as private and not access them
from outside the class.
● Finally, the private attributes and methods cannot be accessed from
outside the class, and attempting to do so will raise an
`AttributeError`.

Write a program to demonstrate parameterized constructor in base class


8 1 4
and derived class
class Animal:
ANSWER def __init__(self, name, species):
self.name = name
self.species = species
print("Animal constructor called")

def display_info(self):
print(f"Name: {self.name}, Species: {self.species}")

class Dog(Animal):
def __init__(self, name, species, breed):
super().__init__(name, species)
self.breed = breed
print("Dog constructor called")

def display_info(self):
super().display_info()
print(f"Breed: {self.breed}")

# Creating an instance of the Dog class


dog = Dog("Buddy", "Canis lupus familiaris", "Golden Retriever")

# Calling the display_info() method on the dog object


dog.display_info()

9 3 4 Write a program to demonstrate constructor with default arguments.

class Person:
def __init__(self, name, age=18, occupation="Unemployed"):
self.name = name
self.age = age
self.occupation = occupation

def display_info(self):
print(f"Name: {self.name}, Age: {self.age}, Occupation:
ANSWER {self.occupation}")

# Creating instances of the Person class with different arguments


person1 = Person("John")
person2 = Person("Jane", 25, "Software Developer")

# Calling the display_info() method on both instances


person1.display_info()
person2.display_info()
10 2 4 Write a program to create a python class and delete objects of that class
using del keyword.
ANSWER class MyClass:
def __init__(self, name):
self.name = name

def display_name(self):
print(f"Name: {self.name}")
# Creating two instances of the MyClass class
obj1 = MyClass("Object 1")
obj2 = MyClass("Object 2")

# Calling the display_name() method on both instances


obj1.display_name()
obj2.display_name()

# Deleting the obj1 object using the del keyword


del obj1

# Trying to call the display_name() method on the deleted


object will raise an AttributeError
try:
obj1.display_name()
except AttributeError:
print("obj1 has been deleted")

# Deleting the obj2 object using the del keyword


del obj2

# Trying to call the display_name() method on the deleted


object will raise an AttributeError
try:
obj2.display_name()
except AttributeError:
print("obj2 has been deleted")

11 2 4 Explain inheritance in python with examples.


ANSWER ● Inheritance is a powerful feature of object-oriented
programming that allows one class to inherit attributes and
methods from another class.
● The class that inherits from another class is called the subclass
or derived class, and the class that is inherited from is called the
superclass or base class.
● In Python, inheritance is implemented using the syntax `class
SubclassName(SuperclassName):`, where `SubclassName` is
the name of the subclass and `SuperclassName` is the name of
the superclass.

Here's an example program that demonstrates inheritance in Python:


class Animal:
def __init__(self, name, species):
self.name = name
self.species = species

def make_sound(self):
print("Some generic sound")

def display_info(self):
print(f"Name: {self.name}, Species: {self.species}")

class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Canine")
self.breed = breed

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

class Cat(Animal):
def __init__(self, name, color):
super().__init__(name, "Feline")
self.color = color

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

# Creating instances of the Animal, Dog, and Cat classes


animal = Animal("Generic Animal", "Unknown Species")
dog = Dog("Fido", "Golden Retriever")
cat = Cat("Whiskers", "Tabby")

# Calling the display_info() method on all three instances


animal.display_info()
dog.display_info()
cat.display_info()

# Calling the make_sound() method on all three instances


animal.make_sound()
dog.make_sound()
cat.make_sound()

● In this example, we define an `Animal` class with an


`__init__()` method that takes two arguments, `name` and
`species`, and sets them as attributes of the object. The
`Animal` class also has a `make_sound()` method that prints out
a generic sound and a `display_info()` method that prints out
the `name` and `species` attributes.
● We then define two subclasses of the `Animal` class, `Dog` and
`Cat`. The `Dog` class has its own `__init__()` method that calls
the superclass's `__init__()` method using the `super()`
function, and sets an additional `breed` attribute. The `Dog`
class also overrides the superclass's `make_sound()` method
with its own implementation. The `Cat` class is defined
similarly, with its own `__init__()` method that sets a `color`
attribute and its own implementation of the `make_sound()`
method.
● We create instances of the `Animal`, `Dog`, and `Cat` classes,
and call the `display_info()` method on all three instances to
demonstrate that they are working correctly. We also call the
`make_sound()` method on all three instances to demonstrate
that the method is overridden in the `Dog` and `Cat` subclasses.
● In this way, inheritance allows us to reuse code from a
superclass in a subclass, while also allowing us to add or
modify functionality in the subclass as needed.
12 2 4 Create a class employee with data members: name, department and
salary. Create suitable methods for reading and printing employee
information.
ANSWER class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary

def get_name(self):
return self.name

def set_name(self, name):


self.name = name

def get_department(self):
return self.department

def set_department(self, department):


self.department = department

def get_salary(self):
return self.salary

def set_salary(self, salary):


self.salary = salary

def print_info(self):
print(f"Name: {self.name}")
print(f"Department: {self.department}")
print(f"Salary: {self.salary}")

# Creating an instance of the Employee class


emp = Employee("John Doe", "Sales", 50000)

# Reading and printing employee information


print(f"Employee name: {emp.get_name()}")
print(f"Employee department: {emp.get_department()}")
print(f"Employee salary: {emp.get_salary()}")

# Changing employee information


emp.set_name("Jane Smith")
emp.set_department("Marketing")
emp.set_salary(60000)

# Printing updated employee information


emp.print_info()

13 3 4 Explain data abstraction in detail.

ANSWER ● Data abstraction is a fundamental concept in object-oriented


programming that allows us to represent complex systems by
defining abstract interfaces and hiding their underlying
implementation details.
● In Python, data abstraction is achieved through the use of
classes and objects.
● data abstraction is about modeling real-world objects as abstract
entities that encapsulate data and behavior, and exposing only
the relevant parts of that entity to the outside world.
● The idea is to simplify the complexity of a system by breaking
it down into smaller, more manageable parts, each of which can
be independently developed and tested.
● In Python, data abstraction is implemented through the use of
access modifiers, such as public, private, and protected, which
allow us to control the visibility of data and methods within a
class.
● Public members are accessible to anyone and can be accessed
from outside the class, while private members are only
accessible within the class and are hidden from the outside
world. Protected members are accessible within the class and its
subclasses, but are not visible to the outside world.
Example
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number
self.__balance = balance

def deposit(self, amount):


self.__balance += amount

def withdraw(self, amount):


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

def get_balance(self):
return self.__balance

# Creating an instance of the BankAccount class


account = BankAccount("12345", 5000)

# Depositing and withdrawing money from the account


account.deposit(2000)
account.withdraw(1000)

# Trying to access the account number and balance directly


(which are private members)
print(account.__account_number) # This will result in an
AttributeError
print(account.__balance) # This will also result in an
AttributeError

# Getting the account balance using the public get_balance()


method
print(account.get_balance())

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

You might also like