This page contains the CBSE Computer Science with Python class 12 Unit-1 chapter 3 Classes in Python. You can find the solutions for chapter 3 of CBSE class 12 Computer Science with Python Exercise. So is the case if you are looking for CBSE class 12 Computer Science with Python related topic Classes in Python questions and answers for the Exercise.
Exercise
Question 1
1. Give one word for the following:
(a)
A sort of constructor in Python (✔ __init__)
(b)
A region of a Python program where a namespace is directly accessible (✔ scope)
(c)
It returns the docstring of a class (✔ __doc__)
(d)
It returns the string representation of the object (✔ __str__)
(e)
A method used to delete an attribute (✔ delattr())
Answer 1
(a)
__init__(b)
scope(c)
__doc__(d)
__str__(e)
delattr()Question 2
2. Define a namespace. Give examples of namespaces with respect to Python.
Answer 2
A namespace is a mapping where names are bound to objects/values.
Examples in Python:
1.
Built-in namespace
2.
Global namespace (module level)
3.
Local namespace (inside functions)
4.
Class/Object namespace (attributes)
Question 3
3. Is data of different types treated differently in Python? Support your answer with an example.
Answer 3
In Python, names (variables) of all types are treated in the same manner. Numbers, strings, functions, modules, and classes are all objects, and a name is simply bound to an object using
=.A name refers to one object at a time, but the same name can refer to different types at different times through reassignment.
Example:
# same variable name 'x' referring to different data types at different times
x = 10
print x
x = "Ten"
print x
x = [10, 20, 30]
print x
Sample Output:
10
Ten
[10, 20, 30]
Question 4
4. Explain LEGB rule.
Answer 4
The LEGB rule is the order in which Python searches for a name (variable/function) in namespaces.
1.
L – Local: Python first checks the local namespace (inside the current function).
2.
E – Enclosing: If not found locally, Python checks the enclosing function namespace (nested functions).
3.
G – Global: If still not found, Python checks the global namespace of the module.
4.
B – Built-in: Finally, Python checks built-in names like
len, sum, and print.Important: If a name is not found in L, E, G, or B, Python raises
NameError.Question 5
5. Is object of a class mutable? Why/why not?
Answer 5
Yes, an object (instance) of a class is mutable in Python.
This is because the state of an object can be changed after it is created. When we call a method on an object, it can modify the object’s data/attributes, so the object does not remain fixed.
Therefore, an object of a class is mutable.
Example:
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
s1 = Student("Amit", 80)
print s1.marks
s1.marks = 95 # object state changed
print s1.marks
Output:
80
95
Question 6
6. Explain the usage of keyword
pass in class definition.Answer 6
In Python,
pass is a null statement. It means “do nothing” and is used as a placeholder.When a class definition is required syntactically but no members are defined yet,
pass keeps the code valid.Example:
class Student:
# Empty class placeholder
pass
Here,
Student is created with no data members and no member functions for now. They can be added later.Question 7
7. What is the use of
__init__? When is it called? Explain with an example.Answer 7
Use of
__init__:__init__ is a special method (constructor) used to initialize an object by assigning initial values to its attributes.When is it called?
It is called automatically when an object (instance) is created.
Example:
class Student:
def __init__(self, name, rollno):
# Initializing data members
self.name = name
self.rollno = rollno
def show(self):
print "Name:", self.name
print "Roll No:", self.rollno
# Object creation (__init__ is called automatically)
s1 = Student("Amit", 12)
s1.show()
Sample Output:
Name: Amit
Roll No: 12
As soon as
s1 = Student("Amit", 12) is executed, Python automatically calls __init__ and stores values in self.name and self.rollno.Question 8
8. Explain the importance of
self in Python classes.Answer 8
self is the first parameter of an instance method in a Python class. It refers to the current object (instance) that calls the method.Using
self, Python knows which object’s attributes should be accessed or modified.Importance of
self:1.
It is used to access instance attributes such as
self.name and self.rollno.2.
It is used to call other methods of the same object.
3.
Without
self, a method cannot identify which object’s data it should use.Example:
class Student:
def __init__(self, name):
self.name = name # belongs to current object
def display(self):
print "Name:", self.name
s1 = Student("Amit")
s2 = Student("Ravi")
s1.display()
s2.display()
Sample Output:
Name: Amit
Name: Ravi
Here,
self.name stores different values for s1 and s2, so each object maintains its own data.Question 9
9. Differentiate between class attributes and instance attributes.
Answer 9
Basis
Class Attributes
Instance Attributes
Meaning
Belong to the class itself.
Belong to a specific object (instance).
Creation Place
Defined in class body, usually outside methods.
Created inside methods (mostly
__init__) using self.Sharing
Shared by all objects of that class.
Separate for each object.
Change Effect
Change may affect all objects that use class-level value.
Change affects only that object.
Access
ClassName.attribute or object.attribute.object.attribute.Example
Student.school = "ABC School"self.name = "Ravi"Small Example:
class Student:
school = "ABC School" # class attribute
def __init__(self, name):
self.name = name # instance attribute
s1 = Student("Ravi")
s2 = Student("Asha")
print Student.school
print s1.school, s1.name
print s2.school, s2.name
Here,
school is common for all students, but name is different for each student object.Question 10
10. Explain
__str__ with an example.Answer 10
__str__ is a special method that returns the string representation of an object.When an object is printed, Python calls this method to decide what text should be shown.
•
If
__str__ is not defined, object printing shows a default representation.•
If
__str__ is defined, we can display object details in a readable form.Example:
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
def __str__(self):
# String returned here is printed for the object
return "Student Name: " + self.name + ", Roll No: " + str(self.roll)
s1 = Student("Amit", 12)
print s1
Sample Output:
Student Name: Amit, Roll No: 12
Here,
print s1 automatically calls s1.__str__() and prints the returned string.Question 11
11. What do you mean by name mangling? Support your answer with relevant example.
Answer 11
Name mangling is Python’s mechanism that gives limited support for private-like data members.
When an attribute starts with double underscores (for example,
__bp), Python changes its internal name to avoid accidental direct access and name clashes.In class
Test, __bp is internally stored as _Test__bp.Example:
class Test:
__bp = 120 # mangled attribute
t = Test()
# print t.__bp # gives error (direct access not allowed)
# Accessing using mangled name
print t._Test__bp
Sample Output:
120
Conclusion: Name mangling does not make an attribute completely hidden, but it makes direct access difficult and helps prevent accidental use outside the class.
Question 12
12. Differentiate between reference counting and automatic garbage collection with respect to Python.
Answer 12
In Python, memory is managed mainly using reference counting and automatic garbage collection.
Basis
Reference Counting
Automatic Garbage Collection
Meaning
Python keeps a count of references to an object.
Python runs a garbage collector to find and remove unused objects.
When Memory Is Freed
When reference count becomes
0, object is removed immediately.Runs automatically when allocation/de-allocation crosses threshold, then clears memory.
Works Best For
Normal cases where references are removed properly.
More complex cases where unused objects still remain in memory.
Simple Example Idea
If
x = None, object may become 0-reference and get removed.Even if objects are left unused, GC eventually checks and cleans them.
In short:
•
Reference counting is the basic continuous method (count becomes zero → delete).
•
Garbage collection is extra automatic cleanup that runs periodically (threshold-based).
Question 13
13. If we want to make the method that is added dynamically to a class available to all the instances of the class, how can it be done? Explain with the help of an example.
Answer 13
To make a dynamically added method available to all instances, bind that method to the class itself, not to a single object.
When added to the class, every current and future object of that class can use it.
Example:
class Demo:
def __init__(self, name):
self.name = name
# normal function (outside class)
def greet(self):
print "Hello", self.name
# dynamic method addition to class
Demo.greet = greet
d1 = Demo("Ravi")
d2 = Demo("Sita")
d1.greet()
d2.greet()
Sample Output:
Hello Ravi
Hello Sita
Here,
greet() was not originally inside Demo. After Demo.greet = greet, it behaves as a class method for every instance.Question 14
14. Predict the output of the following code snippet.
(i)
ptr = 40def result():print(ptr)ptr = 90def func(var):if var <= 60:ptr = 30print ptrresult()func(60)func(70)(ii)
ptr = 50def result():global ptrptr = ptr + 1print ptrresult()print ptrAnswer 14
(i) It raises
UnboundLocalError in result(), because ptr is treated as local after assignment and is printed before assignment.(ii) Output:
51
51
Question 15
15. Name the methods that can be used to:
(a)
access attribute of an object
(b)
delete an attribute of an object
Answer 15
(a)
getattr(obj, name[, default])(b)
delattr(obj, name)Question 16
16. Give the statement to:
(a)
Check whether the attribute
str exists in the class Test whose object is T1.(b)
Assign a value
"Hello" to the attribute str of class Test and object T1.Answer 16
(a)
hasattr(T1, "str")(b)
setattr(T1, "str", "Hello")Question 17
17. Consider the following class definition:
class Yourclass:marks = 10name = "ABC"def __init__(self, marks, name):self.marks = marksself.name = namedef display(self):print self.marksprint self.nameGive the statement to create an object of class
Yourclass.Answer 17
# Creating an object of Yourclass
YC = Yourclass(10, "ABC")
Question 18
18. In the code of Q-13 Q-17, what will be the output if the following command is given (assuming
YC is the object)? YC.display()Answer 18
For
YC = Yourclass(10, "ABC"), output of YC.display() will be:10
ABC
Question 19
19. Predict the output of the following code:
class Match:'"Runs and Wickets"'runs = 281wickets = 5def __init__(self, runs, wickets):self.runs = runsself.wickets = wicketsprint "Runs scored are:", runsprint "Wickets taken are:", wicketsprint "Test.__doc__:", Match.__doc__print "Test.__name__:", Match.__name__print "Test.__module__:", Match.__module__print "Test.__bases__:", Match.__bases__print "Test.__dict__:", Match.__dict__Answer 19
The runs and
print statements for wickets are trying to access undefined variables in the global scope, not class variables. To access class variables, you would need to use Match.runs and Match.wickets.Executing the above code results in the following error:
Runs scored are:
Traceback (most recent call last):
File "class_in_python_q_19_a.py", line 8, in <module>
print "Runs scored are:", runs
NameError: name 'runs' is not defined
ℹ️ Note: The code given above in the question is incorrect because it is trying to print undefined variables in the global scope instead of class variables.
Assuming that the first two print statements are inside the class definition (but outside the
__init__ method), the output will be as follows:Corrected Python Program (version 1):
# Corrected version: print class attributes directly
class Match:
'"Runs and Wickets"'
runs = 281
wickets = 5
def __init__(self, runs, wickets):
self.runs = runs
self.wickets = wickets
print "Runs scored are:", self.runs
print "Wickets taken are:", wickets
print "Test.__doc__:", Match.__doc__
print "Test.__name__:", Match.__name__
print "Test.__module__:", Match.__module__
print "Test.__bases__:", Match.__bases__
print "Test.__dict__:", Match.__dict__
Output of the corrected python code (version 1):
Runs scored are: 281
Wickets taken are: 5
Test.__doc__: "Runs and Wickets"
Test.__name__: Match
Test.__module__: __main__
Test.__bases__: ()
Test.__dict__: {'__module__': '__main__', 'runs': 281, '__doc__': '"Runs and Wickets"', '__init__': <function __init__ at 0x14f5ed9782d0>, 'wickets': 5}
There is another version of the program where in the first two print statements are defined inside the
__init__ method of the class.Corrected Python Program (version 2):
# Corrected version: print inside constructor
class Match:
'"Runs and Wickets"'
runs = 281
wickets = 5
def __init__(self, runs, wickets):
self.runs = runs
self.wickets = wickets
print "Runs scored are:", self.runs
print "Wickets taken are:", wickets
print "Test.__doc__:", Match.__doc__
print "Test.__name__:", Match.__name__
print "Test.__module__:", Match.__module__
print "Test.__bases__:", Match.__bases__
print "Test.__dict__:", Match.__dict__
Output of the corrected python code (version 2):
Test.__doc__: "Runs and Wickets"
Test.__name__: Match
Test.__module__: __main__
Test.__bases__: ()
Test.__dict__: {'__module__': '__main__', 'runs': 281, '__doc__': '"Runs and Wickets"', '__init__': <function __init__ at 0x14f5ed9782d0>, 'wickets': 5}
ℹ️ Note: The first two print statements will not execute until an object of the class is created, because they are inside the
__init__ method. The rest of the print statements will execute immediately when the class is defined.Also note that as the class name is
Match, the print statements should have been actually “Match.__dict__” (and not “Test.__dict__”). But that’s fine, as it is syntactically correct in the context of the example.Question 20
20. Create the class
SOCIETY with the following information:society_namehouse_nono_of_membersflatincomeMethods:
•
An
__init__ method to assign initial values of society_name as “Surya Apartments”, flat as “A Type”, house_no as 20, no_of_members as 3, income as 25000.•
Inputdata() – to read data members(society,house_no,no_of_members&income) and call allocate_flat().•
allocate_flat() – To allocate flat according to incomeIncome
Flat
>=25000
A Type
>=20000 and <25000
B Type
<15000
C Type
•
Showdata() – to display the details of the entire class.Answer 20
class SOCIETY:
# data members
society_name = None
flat = None
house_no = None
no_of_members = None
income = None
def __init__(self):
self.society_name = "Surya Apartments"
self.flat = "A Type"
self.house_no = 20
self.no_of_members = 3
self.income = 25000
def Inputdata(self):
self.society_name = raw_input("Enter Society Name: ")
self.house_no = int(raw_input("Enter House No: "))
self.no_of_members = int(raw_input("Enter No. of Members: "))
self.income = float(raw_input("Enter Income: "))
self.allocate_flat()
def allocate_flat(self):
if self.income >= 25000:
self.flat = "A Type"
elif self.income >= 20000 and self.income < 25000:
self.flat = "B Type"
else:
self.flat = "C Type"
def Showdata(self):
print "Society Name:", self.society_name
print "House No:", self.house_no
print "No. of Members:", self.no_of_members
print "Income:", self.income
print "Flat Type:", self.flat
Question 21
21. Define a class
ITEMINFO in Python with the following description:Data Members
ICode (Item Code),Item (Item Name)Price (price of each item)Qty (quantity in stock)Discount (discount percentage)Netprice (final price)Methods
•
A member function FindDisc( ) to calculate discount as per the following rule:
If Qty <= 10
Discount is 0
If Qty is 11 to 20
Discount is 15
If Qty >= 20
Discount is 20
•
A constructor(
__init__ method) to assign the value with 0 for ICode, Price, Qty, Netprice and Discount and null for Item respectively•
A function
Buy() to allow user to enter values for ICode, Item, Price, Qty and call function FindDisc() to calculate the discount and Netprice(Price*Qty-Discount).•
A Function ShowAll( ) to allow user to view the content of all the data members.
Answer 21
# ITEMINFO class implementation
class ITEMINFO:
ICode = None
Item = None
Price = None
Qty = None
Discount = None
Netprice = None
def __init__(self):
# Initial default values
self.ICode = 0
self.Item = ""
self.Price = 0
self.Qty = 0
self.Discount = 0
self.Netprice = 0
def FindDisc(self):
# Set discount based on quantity
if self.Qty <= 10:
self.Discount = 0
elif self.Qty <= 20:
self.Discount = 15
else:
self.Discount = 20
def Buy(self):
# Read item details from user input
self.ICode = int(raw_input("Enter Item Code: "))
self.Item = raw_input("Enter Item Name: ")
self.Price = float(raw_input("Enter Price: "))
self.Qty = int(raw_input("Enter Quantity: "))
self.FindDisc()
# Compute final net price after discount
total = self.Price * self.Qty
self.Netprice = total - (total * self.Discount / 100)
def ShowAll(self):
# Display all data members
print "Item Code:", self.ICode
print "Item Name:", self.Item
print "Price:", self.Price
print "Quantity:", self.Qty
print "Discount %:", self.Discount
print "Net Price:", self.Netprice