Class 12 Computer Science (Python) – Chapter 2 Object Oriented Programming Concepts
Chapter 2 of Class 12 Computer Science (Python), titled \”Object Oriented Programming Concepts,\” introduces students to the core principles of object-oriented programming (OOP) and its application in Python. This chapter is crucial for building a deeper understanding of how to structure Python programs efficiently, using objects and classes. Students will explore key OOP concepts like inheritance, encapsulation, polymorphism, and abstraction, and learn how to implement these concepts in Python.
What You Will Learn in Chapter 2 – Object Oriented Programming Concepts
This chapter helps students understand the fundamental principles of object-oriented programming, which forms the basis for creating modular and maintainable code. By mastering the core OOP concepts and learning how to apply them in Python, students will be able to write cleaner and more organized code.
Key OOP principles, such as classes, objects, methods, inheritance, and polymorphism, will be discussed in detail to provide students with the tools they need to work with complex software systems.
Key Topics Covered:
Introduction to Object Oriented Programming (OOP)
Object-oriented programming (OOP) is a programming paradigm based on the concept of \”objects,\” which contain both data and methods. OOP promotes reusability, modularity, and scalability in programming.
Python, as an object-oriented language, allows the creation of classes and objects, making it easier to model real-world entities in code.
Classes and Objects
Classes: A class is a blueprint for creating objects. It defines the attributes (data) and methods (functions) that the objects of that class will have.
Objects: An object is an instance of a class. It is created based on the class blueprint and has the properties and behaviors defined by that class.
Methods in Python
Methods are functions defined within a class that operate on objects of that class.
Instance methods: These methods take at least one parameter, usually
self
, which refers to the current object of the class.Class methods: These methods operate on the class itself, rather than the instance of the class.
Static methods: These methods do not depend on class or instance and are independent functions within the class.
Encapsulation
Encapsulation is the bundling of data (attributes) and methods (functions) that operate on the data into a single unit or class.
It hides the internal state of an object and only exposes a controlled interface to interact with the object, ensuring data protection and security.
Inheritance
Inheritance allows one class (subclass or derived class) to inherit the attributes and methods of another class (superclass or base class).
This promotes reusability of code and the creation of hierarchical relationships between classes.
Polymorphism
Polymorphism allows one function or method to behave differently based on the context (different data types or objects).
There are two types of polymorphism: method overloading (same method name with different arguments) and method overriding (a subclass provides a specific implementation of a method defined in the superclass).
Abstraction
Abstraction involves hiding the complex implementation details and showing only the necessary functionality to the user.
In Python, abstraction can be achieved through abstract classes and methods, where the class provides a template for other classes to implement specific behavior.
Constructors and Destructors
Constructors: The
__init__()
method in Python is a constructor used for initializing objects.Destructors: The
__del__()
method is a destructor that is called when an object is destroyed.
NCERT Solutions for Chapter 2 – Object Oriented Programming Concepts
Intext Questions:
Definitions and Explanations:
What is a class in Python?
Define an object and explain how it is created.
What is encapsulation? Give an example.
How does inheritance work in Python? Provide an example.
What is polymorphism, and how is it achieved in Python?
Concepts and Syntax:
Explain the difference between instance methods, class methods, and static methods.
How can you implement abstraction in Python? What role does an abstract class play?
Exercise Questions (Q1–Q8):
Detailed Answers on:
Examples of class and object creation in Python.
Programs demonstrating encapsulation by using private and public attributes.
Inheritance examples where a subclass inherits from a superclass.
Examples of method overloading and overriding.
Implementing abstraction in Python using abstract classes.
Practical Programming Tasks:
Write Python programs to implement OOP concepts such as classes, inheritance, polymorphism, and encapsulation.
Implement programs that use both instance and static methods.
Create a class hierarchy to demonstrate inheritance.
Download Chapter 2 Solutions PDF – Object Oriented Programming Concepts
Get access to our free, comprehensive PDF containing:
All NCERT intext and exercise solutions.
Clear and concise definitions of OOP concepts.
Step-by-step code examples and outputs.
Board-exam-focused short and long answers.
Highlights of Our NCERT Solutions:
Clear Explanations with real-world examples of OOP concepts.
Code Snippets for practical understanding and application.
Step-by-Step Solutions to break down complex topics like inheritance and polymorphism.
Visual Aids such as class diagrams and flowcharts for better understanding.
Quick Revision: Exam-focused answers for short and long questions.
Recommended Preparation Tips:
Understand Classes and Objects: Practice creating classes and objects, and get comfortable with object initialization using constructors.
Master Inheritance and Polymorphism: These are key concepts for writing reusable and flexible code in Python.
Practice Encapsulation: Implement getter and setter methods to control access to private attributes and ensure data security.
Work on Abstraction: Implement abstract classes and methods to understand how to hide complexity and expose only essential parts of your program.
Write Programs: Implement Python programs that incorporate OOP principles to reinforce your understanding.
Additional Study Resources:
Flashcards for Key Terms (Class, Object, Encapsulation, Polymorphism, etc.)
Flowchart Practice Sheets for inheritance hierarchies and class relationships.
Past Year CBSE Questions on Object Oriented Programming.
Online Quizzes and Mock Tests on OOP concepts in Python.
Mastering Chapter 2 – Object Oriented Programming Concepts
Mastering the concepts in this chapter is crucial for building a strong foundation in object-oriented programming and applying these principles to develop complex Python applications. Understanding and implementing OOP concepts like inheritance, encapsulation, polymorphism, and abstraction will enable you to write clean, maintainable, and reusable code.
Ideal for CBSE Board Exams and entrance exams like CUET, this chapter prepares students for advanced programming tasks and real-world application development.
Class 12 Computer Science (Python) – Chapter 2 Object Oriented Programming Concepts
NCERT Textbook Questions Solved – Class 12 Computer Science (Python)
TOPIC-1: General OOP Concepts
Short Answer Type Questions (2 marks)
Question 1:
How is a static method different from an instance method?
Answer:
A static method has to be defined outside a class. It can be called without an object.
An instance method is defined within a class and has to be invoked on an object.
Question 2:
Explain Data Hiding with respect to OOP.
Answer:
Data hiding can be defined as the mechanism of hiding the data of a class from the outside world or, more precisely, from other classes. Data hiding is achieved by making the members of the class private. Access to private members is restricted and is only available to the member functions of the same class. However, the public part of the object is accessible outside the class.
Question 3:
Fill in the blanks:
- Act of representing essential features without background detail is called ______.
- Wrapping up of data and associated functions into a single unit is called ______.
- ______ is called the instance of a class.
Answer:
Data Abstraction
Encapsulation
Object
Question 4:
What is Object Oriented Programming? List some of its advantages.
Answer:
OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. Advantages:
- Simplicity
- Modifiability
- Extensibility and Maintainability
- Reusability
- Security
Question 5:
Differentiate between an object and a class.
Answer:
A class is a collection of objects of similar type. For example, mango, apple, and orange are members of the class \”fruit.\” Classes are user-defined data types and behave like the built-in types of a programming language.
The syntax used to create an object is not different than the syntax used to create an integer object in C. If \”fruit\” has been defined as a class, then the statement fruit mango;
will create an object \”mango\” belonging to the class \”fruit.\”
Question 6:
Explain polymorphism with an example.
Answer:
Polymorphism is the ability for a message or data to be processed in more than one form. An operation may exhibit different behaviors in different instances. For example, consider the operation of addition of two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation.
Question 7:
List three features that make an important characteristic of OOP.
Answer:
- Capability to express closeness with the real-world models.
- Reusability – allows addition of new features to an existing one.
- Transitivity – changes in one class get automatically reflected across.
Question 8:
How do we implement an abstract method in Python? Give an example for the same.
Answer:
An abstract method is an unimplemented method. When an abstract method is declared in a base class, the derived class must define the method or raise a \”NotImplementedError\”.
Example:
class Shape(object): def findArea(self): pass class Square(Shape): def __init__(self, side): self.side = side def findArea(self): return self.side * self.side
Question 9:
List a few disadvantages of OOP.
Answer:
- Classes tend to be overly generalized.
- Relationships among classes might become artificial.
- Program design is tricky and complicated.
- More skills and thinking in terms of objects is required.
Question 10:
Explain Function overloading with an example.
Answer:
When several function declarations are specified for a single function name in the same scope, the function is said to be overloaded. In other languages, the same function name can be used to define multiple functions with different numbers and types of arguments.
Example:
def test(): # function 1 print(\"hello\") def test(a, b): # function 2 return a + b def test(a, b, c): # function 3 return a + b + c
Question 11: What is inheritance? Explain with an example.
Answer:
Inheritance is an object-oriented programming feature that allows one class (the child class) to inherit properties and behaviors (methods) from another class (the parent class). For example, in a class hierarchy, the class \”Bird\” can be a parent class, while the \”Parrot\” class can inherit characteristics like the ability to fly from the \”Flying Bird\” class, which in turn inherits from \”Bird.\”
Question 12: How are data encapsulation and data abstraction implemented in Python? Explain with an example.
Answer:
Encapsulation: It involves wrapping data and methods into a single unit, i.e., a class. We achieve encapsulation by defining data as private (using private variables) and providing methods to access and modify it.
Abstraction: It involves hiding the complexity of implementation from the outside world, showing only essential features. This is done by defining abstract methods in a base class, which must be implemented by derived classes.
For example, in a Student
class, details like name and roll number might be exposed, while grade calculations could be kept private, hidden from outside access.
Question 13: Consider the figure given below and answer the questions that follow:
Answer:
- Base class: STUDENT
- Derived classes: GRADUATE, POST GRADUATE
- Concept Implemented: Inheritance
Question 14: What is an abstract method? Give a suitable example to illustrate the same.
Answer:
An abstract method is a method that is declared in a parent class but does not have any implementation. Subclasses must provide the specific implementation of the abstract method. For example:
class Teacher: def entry(self): pass def display(self): print(self, teach)
In this example, the entry
method is abstract, and any derived class must implement this method.
Question 15: What is the concept of overriding a method? Give an example for the same.
Answer:
Method overriding is when a child class provides a specific implementation for a method that is already defined in the parent class. It allows the child class to alter the behavior of the inherited method.
Example:
class Emp: def __init__(self, name): self.name = name class Manager(Emp): def __init__(self, name, department): super().__init__(name) self.department = department
Here, the Manager
class overrides the __init__
method of the Emp
class.
Question 16: Is function overloading supported by Python? Give reasons.
Answer:
No, Python does not support function overloading in the traditional sense. You cannot define multiple functions with the same name but different parameters. However, Python allows dynamic function dispatch using default arguments or variable-length arguments. So, instead of overloading functions, you can handle multiple cases in a single function using *args
or **kwargs
.
Question 17: Predict the output of the following program. Also, state which concept of OOP is being implemented?
def sum(x, y, z): print(\"sum =\", x + y + z) def sum(a, b): print(\"sum =\", a + b) sum(10, 20) sum(10, 20, 30)
Output:
TypeError: sum() takes exactly 3 arguments (2 given)
Concept: Polymorphism (Function Overloading)
In this case, Python doesn\’t support traditional function overloading. The second definition of sum
overwrites the first, causing the error when the function is called with two arguments instead of three.
Question 18: Define binding. Differentiate between static and dynamic binding.
Answer:
Binding refers to the association between a function call and its definition. This process links the function call to the corresponding code for execution.
- Static Binding: This occurs at compile time, meaning the function to be called is resolved during the compilation process. It is often used in languages like C++.
- Dynamic Binding: This happens at runtime. The function that needs to be called is determined when the program is executed, which allows for more flexibility (e.g., in Python).
Long Answer Type Questions (4 marks)
Question 1:
Write a program that uses an area()
function for the calculation of the area of a triangle, rectangle, or square. The number of sides (3, 2, or 1) suggests the shape for which the area is to be calculated.
from functools import wraps import math def overloaded(func): @wraps(func) def overloaded_func(*args, **kwargs): for f in overloaded_func.overloads: try: return f(*args, **kwargs) except TypeError: pass raise TypeError(\"No compatible signatures\") def overload_with(func): overloaded_func.overloads.append(func) return overloaded_func overloaded_func.overloads = [func] overloaded_func.overload_with = overload_with return overloaded_func @overloaded def area(): print(\'Area\') pass @area.overload_with def _(a): print(f\'Area of square = {a * a}\') @area.overload_with def _(a, b): print(f\'Area of rectangle = {a * b}\') @area.overload_with def _(a, b, c): s = (a + b + c) / 2 print(f\'Area of triangle = {math.sqrt(s * (s - a) * (s - b) * (s - c))}\') choice = int(input(\"Enter 1 for square, 2 for rectangle, 3 for triangle: \")) if choice == 1: side = int(input(\"Enter side: \")) area(side) elif choice == 2: length = int(input(\"Enter length: \")) breadth = int(input(\"Enter breadth: \")) area(length, breadth) elif choice == 3: a = int(input(\"Enter side 1: \")) b = int(input(\"Enter side 2: \")) c = int(input(\"Enter side 3: \")) area(a, b, c) else: print(\"Invalid choice\")
Question 2:
Write a program to find the volume of a cube, cuboid, and cylinder using function overloading.
from functools import wraps import math def overloaded(func): @wraps(func) def overloaded_func(*args, **kwargs): for f in overloaded_func.overloads: try: return f(*args, **kwargs) except TypeError: pass raise TypeError(\"No compatible signatures\") def overload_with(func): overloaded_func.overloads.append(func) return overloaded_func overloaded_func.overloads = [func] overloaded_func.overload_with = overload_with return overloaded_func @overloaded def volume(): print(\'Volume\') pass @volume.overload_with def _(a): print(f\'Volume of cube = {a * a * a} cubic units\') @volume.overload_with def _(a, b): print(f\'Volume of cylinder = {3.14 * a * a * b} cubic units\') @volume.overload_with def _(a, b, c): print(f\'Volume of cuboid = {a * b * c} cubic units\') choice = int(input(\"Enter 1 for cube, 2 for cylinder, 3 for cuboid: \")) if choice == 1: side = int(input(\"Enter side: \")) volume(side) elif choice == 2: radius = int(input(\"Enter radius: \")) height = int(input(\"Enter height: \")) volume(radius, height) elif choice == 3: length = int(input(\"Enter length: \")) breadth = int(input(\"Enter breadth: \")) height = int(input(\"Enter height: \")) volume(length, breadth, height) else: print(\"Invalid choice\")
Question 3:
Write a class CITY
in Python with the following specifications:
Attribute | Details |
---|---|
Code | Numeric value |
Name | String value |
Pop | Numeric value for Population |
KM | Numeric value |
Density | Numeric value for Population Density |
Methods:
CalDen()
– Method to calculate Density asPop / KM
.Record()
– Method to allow the user to enter values forCode
,Name
,Pop
,KM
, and callCalDen()
method.See()
– Method to display all the data members and display a message “Highly Populated Area” if the density is more than 12000.
class CITY: def __init__(self): self.Code = 0 self.Name = \"\" self.Pop = 0 self.KM = 0 self.Density = 0 def CalDen(self): self.Density = self.Pop / self.KM def Record(self): self.Code = int(input(\"Enter Code: \")) self.Name = input(\"Enter Name: \") self.Pop = int(input(\"Enter Population: \")) self.KM = int(input(\"Enter KM: \")) self.CalDen() def See(self): print(f\"Code: {self.Code}, Name: {self.Name}, Population: {self.Pop}, Area: {self.KM}, Density: {self.Density}\") if self.Density > 12000: print(\"Highly Populated Area\")
Question 4:
Give a suitable example using Python code to illustrate single-level inheritance considering COUNTRY
to be the base class and STATE
to be the derived class.
class COUNTRY: state_list = [] def __init__(self, name): self.name = name class STATE(COUNTRY): def __init__(self, name, capital): super().__init__(name) self.capital = capital
Question 5:
Write a class DISTRICT
in Python with the following specifications:
Attribute | Details |
---|---|
Dcode | Numeric value |
DName | String value |
People | Numeric value for Population |
Area | Numeric value |
Density | Numeric value for Population Density |
class DISTRICT: def __init__(self, Dcode, DName, People, Area, Density): self.Dcode = Dcode self.DName = DName self.People = People self.Area = Area self.Density = Density def display(self): print(f\"District Code: {self.Dcode}\") print(f\"District Name: {self.DName}\") print(f\"Population: {self.People}\") print(f\"Area: {self.Area}\") print(f\"Density: {self.Density}\")
Question 6:
Answer the question (i) to (iv) based on the following:
class Shop: def __init__(self): self.no_of_employees = 0 self.no_of_brands = 0 def getSdate(self): self.no_of_employees = int(input(\"Number of employees: \")) self.no_of_brands = int(input(\"Number of brands: \")) def showSdate(self): print(self.no_of_employees) print(self.no_of_brands) class Brand: def __init__(self): self.name = \"\" self.category = [\"Mens\", \"Womens\", \"Kids\"] self.avgprice = 0 def getdate(self): self.name = input(\"Enter Brand Name: \") self.avgprice = float(input(\"Enter Average Price: \")) def showdate(self): print(self.name) print(self.category) print(self.avgprice) class Mall(Brand, Shop): def showdate(self): self.no_of_shops = 0 def getdate(self): super(Mall, self).getSdate() super(Mall, self).getdate() self.no_of_shops = int(input(\"Enter number of shops: \")) def showdata(self): print(self.no_of_shops) print(self.no_of_brands)
- Type of Inheritance: Multiple Inheritance
- Explanation of Statements 1 and 2:
- Statement 1 invokes the
getSdate()
function of classShop
. - Statement 2 invokes the
getdate()
function of classBrand
.
- Statement 1 invokes the
- Methods Overridden:
getdate()
method of classBrand
is overridden in classMall
. - Blank 1:
print(self.category)
Short Answer Type Questions (2 marks)
Question 1:
Give one word for the following:
Item | Answer |
---|---|
A sort of constructor in Python | __init__ |
A region of a Python program where a namespace is directly accessible | scope |
It returns the docstring of a class | __doc__ |
It returns the string representation of the object | __str__ |
A method used to delete an attribute | _delattr_() |
Question 2:
Define a namespace. Give examples of namespaces with respect to Python.
A namespace is a mapping from names to objects. Examples of namespaces include:
- Built-in namespace (contains all the built-in objects in Python).
- Global namespace (contains all objects defined at the level of a script or module).
- Local namespace (contains all objects defined within a function).
Question 3:
What is the significance of the super
method? Give one example of the same.
The super()
function is used to call methods from the base class, particularly when they have been overridden in the derived class.
class Student: def __init__(self): self.name = \"\" def readStudent(self): print(\"Reading student details\") class GradStudent(Student): def __init__(self): super().__init__() self.subject = \"\" self.working = \"\" def readGrad(self): super().readStudent() # Calls the readStudent method of parent class
Question 4:
Explain the LEGB rule.
The LEGB rule defines the order in which Python searches for a name. The order is:
- L: Local namespace (within the current function)
- E: Enclosing namespace (any enclosing function)
- G: Global namespace (module-level objects)
- B: Built-in namespace (built-in Python objects)
Question 5:
Write a class DISTRICT in Python with the following specification:
Instance Attributes
- Dcode # Numeric value
- DName # String value
- People # Numeric value for Population
- Area # Numeric value
- Density # Numeric value for Population Density
Answer:
class DISTRICT: def __init__(self, Dcode, DName, People, Area, Density): self.Dcode = Dcode self.DName = DName self.People = People self.Area = Area self.Density = Density def display(self): print(\"District Code:\", self.Dcode) print(\"District Name:\", self.DName) print(\"Population:\", self.People) print(\"Area:\", self.Area) print(\"Density:\", self.Density)
Question 6:
Answer the question (i) to (iv) based on the following:
Class Shop (object):
class Shop: def __init__(self): self.no_of_employees = 0 self.no_of_brands = 0 def getSdate(self): self.no_of_employees = input(\"Number of employees: \") self.no_of_brands = input(\"Number of brands: \") def showSdate(self): print(self.no_of_employees) print(self.no_of_brands) class Brand(object): def __init__(self): self.name = \"\" self.category = (\"Mens\", \"Womens\", \"Kids\") self.avgprice = 0.0 def getdata(self): self.name = input(\"Enter Brand Name: \") self.avgprice = float(input(\"Enter Average Price: \")) def showdata(self): print(self.name) print(self.category) print(self.avgprice) class Mall(Brand, Shop): def __init__(self): super().__init__() self.no_of_shops = 0 def getdata(self): super(Mall, self).getSdate() super(Mall, self).getdata() self.no_of_shops = input(\"Enter number of shops: \") def showdata(self): print(self.no_of_shops) print(self.no_of_brands)
Which type of inheritance is demonstrated in the above code?
Answer:
Multiple Inheritance
Statement 1 and 2 Explanation:
Statement 1 and 2 invoke the getSdate() function of class Shop and getdata() function of class Brand, respectively.
Methods that are overridden:
- getdata() method of class Brand is overridden. When an object of class Mall is created and
M = Mall()
is called, thegetdata()
method of class Mall is invoked, not that of class Brand.
Blank 1 Explanation:
print(self.category)
Topic 2: Classes
Short Answer Type Questions (2 marks)
Question 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_()
Question 2:
Define a namespace. Give examples of namespaces with respect to Python.
Namespace is a mapping from names to objects. Examples of namespaces are built-in names, global names in a module, and local names in function invocation.
Question 3:
What is the significance of super method? Give one example of the same.
The super()
function is used to call base class methods which have been extended in the derived class.
Example:
class GradStudent(Student): def __init__(self): super(GradStudent, self).__init__() self.subject = \"\" self.working = \"\" def readGrad(self): super(GradStudent, self).readStudent()
Question 4:
Explain LEGB rule.
LEGB rule: When a name is encountered during the execution of the program, it searches for that name in the following order:
- L. Local – It first makes a local search, i.e., in the current function scope.
- E. Enclosing functions – It searches in all enclosing functions, from inner to outer.
- G. Global (module) – It searches for global modules or for names declared global.
- B. Built-in (Python) – Finally, it checks for any built-in functions in Python.
Question 5:
Is an object of a class mutable? Why/why not?
Yes, user-defined classes are considered mutable. Python doesn’t have absolutely private attributes, so you can always change an object\’s state and attributes.
Question 6:
Explain the usage of keyword ‘pass’ in class definition.
When a class doesn’t define any methods or attributes but syntactically needs to have something in the definition, we use the pass
keyword. It does nothing and acts as a placeholder.
Question 7:
What is the use of __init__? When is it called? Explain with an example.
__init__
helps to create objects and initialize instances of the class. It reserves memory for the members of the class.
Example:
class MyClass: def __init__(self): self.attribute = 5
Question 8:
Explain the importance of self in Python classes.
self
is an object reference to the object itself. It is used to refer to instance attributes and methods from within the class. It is important because Python methods are called in the context of an instance of the class.
Question 9:
Differentiate between class attributes and instance attributes.
Class attributes are shared by all instances, whereas instance attributes are unique to each instance of the class.
Question 10:
Explain __str__ with an example.
__str__
returns a string representation of an object. It overrides the default behavior of the Python built-in str()
function.
Example:
class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f\"({self.x}, {self.y})\"
Question 11:
What do you mean by name mangling? Support your answer with relevant example.
Name mangling is the process of changing the name of an attribute or method to prevent accidental overriding or to simulate \”private\” variables. In Python, this is done by prefixing the name with double underscores.
Example:
class MyClass: def __init__(self): self.__private = 10 def get_private(self): return self.__private
Question 12:
Differentiate between reference counting and automatic garbage collection with respect to Python.
Reference Counting: The Python memory management system keeps track of the number of references to each object. When an object\’s reference count reaches zero, it is automatically deleted.
Automatic Garbage Collection: Python also uses garbage collection, which is a process to reclaim memory by removing unused objects when they are no longer needed.
Question 13:
Predict the output of the following code snippet:
ptr = 40 def result(): print(ptr) ptr = 90 def func(var): if var <= 60: ptr = 30 print(ptr) result() func(60) func(70)
Answer:
UnboundLocalError: local variable \'ptr\' referenced before assignment.
Question 14:
What is the difference between Multilevel inheritance and Multiple inheritance? Give suitable examples to illustrate.
Multilevel inheritance occurs when a class is derived from another derived class. Multiple inheritance occurs when a class is derived from more than one base class.
Question 15:
How do you implement an abstract method in Python? Give an example for the same.
An abstract method is an unimplemented method. If a base class has an abstract method, the derived class must implement it or raise a NotImplementedError.
Example:
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def findArea(self): pass class Square(Shape): def __init__(self, side): self.side = side def findArea(self): return self.side * self.side
Question 16
Predict the output of the following code:
ptr = 50 def result(): global ptr ptr = ptr + 1 print(ptr) result() print(ptr)
Answer:
The output will be:
51 51
Explanation: The global
keyword allows us to modify the value of ptr
within the function, which results in the value of ptr
becoming 51 after the function is called.
Question 17
Name the methods used to:
- Access an attribute of an object.
- Delete an attribute of an object.
Answer:
- To access an attribute of an object:
getattr(obj, name[, default])
- To delete an attribute of an object:
delattr(obj, name)
Question 18
Give the statements to:
- Check whether the attribute
str
exists in the classTest
whose object isT
. - Assign the value \"Hello\" to the attribute
str
of classTest
and objectT
.
Answer:
- To check if the attribute
str
exists:hasattr(T, \'str\')
- To assign the value \"Hello\" to
str
:setattr(T, \'str\', \'Hello\')
Question 19
Predict the output of the following code:
class Match: # “Runs and Wickets” runs = 281 wickets = 5 def __init__(self, runs, wickets): self.runs = runs self.wickets = wickets print(\"Runs scored are :\", runs) print(\"Wickets taken are :\", wickets) print(\"Match.__doc__:\", Match.__doc__) print(\"Match.__name__:\", Match.__name__) print(\"Match.__module__:\", Match.__module__) print(\"Match.__bases__:\", Match.__bases__) print(\"Match.__dict__:\", Match.__dict__) # Create an object m = Match(100, 4)
Answer:
The output will be:
Runs scored are : 100 Wickets taken are : 4 Match.__doc__: None Match.__name__: Match Match.__module__: __main__ Match.__bases__: (,) Match.__dict__: {\'__module__\': \'__main__\', \'__doc__\': None, \'runs\': 281, \'__init__\': , \'wickets\': 5}
Explanation: This code prints the constructor details, including the class\'s __dict__
, __doc__
, and other internal attributes.
Long Answer Type Questions
Question 1: Customer Class
Write a class customer
in Python containing:
- Instance attributes:
customernumber
,customemame
,price
,qty
,discount
,totalprice
,netprice
- Methods:
__init__()
,caldiscount()
,input()
,show()
Answer:
class Customer: def __init__(self): self.customernumber = 111 self.customemame = \'Leena\' self.qty = 0 self.price = 0 self.discount = 0 self.netprice = 0 def caldiscount(self): totalprice = self.price * self.qty if totalprice >= 50000: self.discount = totalprice * 0.25 elif totalprice >= 25000: self.discount = totalprice * 0.15 else: self.discount = totalprice * 0.10 self.netprice = totalprice - self.discount def input(self): self.customernumber = input(\"Enter Customer Number\") self.customemame = input(\"Enter Customer Name\") self.qty = int(input(\"Enter Quantity\")) self.price = float(input(\"Enter Price\")) self.caldiscount() def show(self): print(\"Customer Number:\", self.customernumber) print(\"Customer Name:\", self.customemame) print(\"Quantity:\", self.qty) print(\"Price:\", self.price) print(\"Discount:\", self.discount) print(\"Net Price:\", self.netprice) # Example usage customer = Customer() customer.input() customer.show()
Question 2: SOCIETY Class
Create the class SOCIETY
with the following information:
- Attributes:
society_name
,house_no
,no_of_members
,flat
,income
- Methods:
Inputdata()
,Allocate_Flat()
,ShowData()
Answer:
class Society: def __init__(self): self.society_name = \'Surya Apartments\' self.house_no = 20 self.no_of_members = 3 self.flat = \'AType\' self.income = 25000 def Inputdata(self): self.society_name = input(\"Enter Society Name\") self.house_no = int(input(\"Enter House Number\")) self.no_of_members = int(input(\"Enter No. of members\")) self.income = float(input(\"Enter income\")) def Allocate_Flat(self): if self.income >= 25000: self.flat = \'AType\' elif self.income >= 20000: self.flat = \'BType\' else: self.flat = \'CType\' def ShowData(self): print(\"Society Name:\", self.society_name) print(\"House No:\", self.house_no) print(\"No. of Members:\", self.no_of_members) print(\"Flat Type:\", self.flat) print(\"Income:\", self.income) # Example usage society = Society() society.Inputdata() society.Allocate_Flat() society.ShowData()
Question 3: ITEMINFO Class
Define a class ITEMINFO
in Python with the following description:
- Attributes:
ICode
,Item
,Price
,Qty
,Discount
,Netprice
- Methods:
FindDisc()
,Buy()
,ShowAll()
Answer:
class ItemInfo: def __init__(self): self.ICode = 0 self.Item = \'\' self.Price = 0.0 self.Qty = 0 self.Discount = 0 self.Netprice = 0.0 def Buy(self): self.ICode = input(\"Enter Item Code\") self.Item = input(\"Enter Item Name\") self.Price = float(input(\"Enter Price\")) self.Qty = int(input(\"Enter Quantity\")) def FindDisc(self): if self.Qty <= 10: self.Discount = 0 elif self.Qty <= 20: self.Discount = 15 else: self.Discount = 20 self.Netprice = self.Price * self.Qty - self.Discount def ShowAll(self): print(\"Item Code:\", self.ICode) print(\"Item Name:\", self.Item) print(\"Price:\", self.Price) print(\"Quantity:\", self.Qty) print(\"Net Price:\", self.Netprice) # Example usage item = ItemInfo() item.Buy() item.FindDisc() item.ShowAll()
Question 4: PRODUCT Class
Write a Python program for the class PRODUCT
with:
- Attributes:
Pid
,Pname
,Peostprice
,Psellingprice
,Margin
,Remarks
- Methods:
SetRemarks()
,Getdetails()
,Setdetails()
Answer:
class Product: def __init__(self): self.Pid = \'\' self.Pname = \'\' self.Peostprice = 0.0 self.Psellingprice = 0.0 self.Margin = 0.0 self.Remarks = \'\' def SetRemarks(self): self.Margin = self.Psellingprice - self.Peostprice if self.Margin < 0: self.Remarks = \"Loss\" else: self.Remarks = \"Profit\" def Getdetails(self): self.Pid = input(\"Enter Product Id\") self.Pname = input(\"Enter Product Name\") self.Peostprice = float(input(\"Enter Cost Price\")) self.Psellingprice = float(input(\"Enter Selling Price\")) self.SetRemarks() def Setdetails(self): print(\"Product Id:\", self.Pid) print(\"Product Name:\", self.Pname) print(\"Cost Price:\", self.Peostprice) print(\"Selling Price:\", self.Psellingprice) print(\"Margin:\", self.Margin) print(\"Remarks:\", self.Remarks) # Example usage product = Product() product.Getdetails() product.Setdetails()
Question 5:
Write a Python program using classes and objects to simulate the result preparation system for 20 students. The data available for each student includes: Name, Roll No, and Marks in 3 subjects. The percentage marks and grade are to be calculated from the following information. Also, demonstrate constructor overloading.
class Student:
# Constructor to create an object
def __init__(self, s=None):
if s is None:
self.rollno = 0
self.name = \'\'
self.marks = [0, 0, 0]
self.avg = 0.0
self.grade = \'\'
else:
self.rollno = s.rollno
self.name = s.name
self.marks = s.marks
self.avg = s.avg
self.grade = s.grade
def read(self):
# This function gets the details of a student from the user
self.rollno = int(input(\"Enter roll number: \"))
self.name = input(\"Enter name: \")
total_marks = 0
for i in range(3):
self.marks[i] = int(input(f\"Enter marks for subject {i+1}: \"))
total_marks += self.marks[i]
self.avg = total_marks / 3
# Calculate grade based on average
if self.avg > 60:
self.grade = \'A\'
elif self.avg > 40:
self.grade = \'B\'
else:
self.grade = \'C\'
def display(self):
# This function prints each student’s details
print(f\"{self.rollno}t{self.name}tt{self.grade}\")
# Create an empty list to store student objects
students = []
num = int(input(\"Enter the number of students: \"))
# Reading student details
for i in range(num):
student = Student()
student.read()
students.append(student)
# Displaying the results
print(\"STUDENT REPORT\")
print(\"***********************************\")
print(\"RollNotNamettGrade\")
print(\"*******************************************\")
for student in students:
student.display()
# Calculate the class average and topper
max_avg = students[0].avg
total_avg = 0
topper = students[0].name
for student in students:
total_avg += student.avg
if student.avg > max_avg:
max_avg = student.avg
topper = student.name
total_avg /= num
print(f\"Class topper is {topper} with average {max_avg}\")
print(f\"Class average is {total_avg}\")
Question 6:
Define a class `SUPPLY` in Python with the following description:
- Private Members: `Code` of type int, `FoodName` of type string, `FoodType` of type string, `Sticker` of type string
- A member function `GetType()` to assign the following values for Food Type as per the given Sticker
- A function `FoodIn()` to allow the user to enter values for `Code`, `FoodName`, `Sticker`, and call the function `GetType()` to assign the respective `FoodType`.
- A function `FoodOut()` to allow the user to view the contents of all the data members.
class SUPPLY:
# Constructor to create an object
def __init__(self):
self.FoodCode = 0
self.FoodName = \'\'
self.FoodType = \'\'
self.Sticker = \'\'
def FoodIn(self):
# Input function for Food details
self.FoodCode = int(input(\"Enter Food Code: \"))
self.FoodName = input(\"Enter Food Name: \")
self.Sticker = input(\"Enter Sticker Colour: \")
def GetType(self):
# Assign Food Type based on Sticker Colour
if self.Sticker == \'GREEN\':
self.FoodType = \'Vegetarian\'
elif self.Sticker == \'YELLOW\':
self.FoodType = \'Contains Egg\'
elif self.Sticker == \'RED\':
self.FoodType = \'Non-Vegetarian\'
else:
self.FoodType = \'Not Known\'
def FoodOut(self):
# Output the details of the food item
print(f\"Food Code: {self.FoodCode}\")
print(f\"Food Name: {self.FoodName}\")
print(f\"Food Type: {self.FoodType}\")
print(f\"Sticker: {self.Sticker}\")
# Creating an object of SUPPLY class and using the methods
s = SUPPLY()
s.FoodIn()
s.GetType()
s.FoodOut()
TOPIC-3: Inheritance
Very Short Answer Type Questions (1 mark)
Question 1:
Give one example for an abstract method.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
Question 2:
Define the term inheritance.
Inheritance is a mechanism where a new class is derived from an existing class, inheriting its properties and methods. The class from which the new class is derived is called the parent class, and the new class is called the child or subclass. It helps in code reusability and organization.
Question 3:
What is single inheritance?
Single inheritance occurs when a subclass is derived from a single base class, meaning it inherits the properties and methods of only one parent class.
Question 4:
What is multiple inheritance? Explain with an example.
Multiple inheritance occurs when a class inherits from more than one base class. This allows the subclass to inherit properties and methods from multiple parent classes.
class ClassA:
def methodA(self):
print(\"Method A from ClassA\")
class ClassB:
def methodB(self):
print(\"Method B from ClassB\")
class ClassC(ClassA, ClassB):
def methodC(self):
print(\"Method C from ClassC\")
c = ClassC()
c.methodA() # Inherited from ClassA
c.methodB() # Inherited from ClassB
Question 5:
Give one example of multilevel inheritance.
In multilevel inheritance, a class derives from another derived class. For example, a class `Country` can be the base class of `State`, and `City` can be the derived class of `State`.
class Country:
def country_name(self):
print(\"Country Name\")
class State(Country):
def state_name(self):
print(\"State Name\")
class City(State):
def city_name(self):
print(\"City Name\")
c = City()
c.country_name() # Inherited from Country
c.state_name() # Inherited from State
c.city_name() # From City
Question 6:
Find the output of the following code and write the type of inheritance:
p = Gstudent(\'Mona\', 20, 12, 99, \'computer\')
class Gstudent(Student):
def __init__(self, name, age, rollno, marks, stream):
super().__init__(name, age, rollno, marks)
self.stream = stream
def display2(self):
self.display()
print(\"Stream:\", self.stream)
p = Gstudent(\'Mona\', 20, 12, 99, \'Computer\')
p.display2()
Type of inheritance: Multilevel inheritance
Output:
Name: Mona Age: 20 Roll No: 12 Marks: 99 Stream: computer
Question 7:
Rewrite the following code after removing errors. Underline each correction and write the output after correcting the code:
class First(): def __init__(self): print(\"First\") class Second(object): def __init__(self): print(\"Second\") class Third(First, Second): def __init__(self): First.__init__(self) Second.__init__(self) print(\"That\'s it\") t = Third()
Question 8: Complete the following code
class employee(object): def __init__(self, no, name, age): self.no = no self.name = name self.age = age def printval(self): print(\"Number:\", self.no) print(\"Name:\", self.name) print(\"Age:\", self.age) class pay(object): def __init__(self, dept, salary): self.dept = dept self.salary = salary def display(self): self.printval() print(self.dept) print(self.salary)Long Answer Type Questions (4 marks)
Question 1: Write a Python program to demonstrate multiple inheritance.
class student(object): def __init__(self): self.mo = 0 self.m1 = 0 self.m2 = 0 def get(self): self.mo = int(input(\"Enter the Roll no: \")) print(\"Enter 2 marks\") self.m1 = int(input(\"Mark1? \")) self.m2 = int(input(\"Mark2? \")) class sports(object): def __init__(self): self.sm = 0 def getsm(self): self.sm = int(input(\"Enter the sports mark: \")) class statement(student, sports): def __init__(self): super(statement, self).__init__() def display(self): tot = (self.m1 + self.m2 + self.sm) avg = tot / 3 print(\"nntRoll No. :\", self.mo, \"ntTotal:\", tot) print(\"tAverage:\", avg) obj = statement() obj.get() obj.getsm() obj.display()Question 2: Create a class for accommodation, meals, and customer with inheritance.
class Accommodation(object): def __init__(self): self.roomno = 0 self.roomtype = \"\" self.roomrent = 0.0 def getroom(self): self.roomno = int(input(\"Enter the Room no: \")) self.roomtype = input(\"Enter the Room type: \") self.roomrent = float(input(\"Enter Room Rent: \")) class Meals(object): def __init__(self): self.mealcode = 0 self.mealname = \"\" self.mealprice = 0.0 def getmeals(self): self.mealcode = int(input(\"Enter the meal code: \")) self.mealname = input(\"Enter the meal name: \") self.mealprice = float(input(\"Enter the meal price: \")) class Customer(Accommodation, Meals): def __init__(self): super(Customer, self).__init__() self.custnum = 0 self.custname = \'\' self.address = \'\' def getCustomer(self): self.custnum = int(input(\"Enter the customer number: \")) self.custname = input(\"Enter customer name: \") self.address = input(\"Enter customer address: \") def displaybill(self): print(\"Customer Name:\", self.custname, \"Address:\", self.address) print(\"Room No:\", self.roomno, \"Room Type:\", self.roomtype, \"Room Rent: Rs\", self.roomrent) print(\"Meal Name:\", self.mealname, \"Price:\", self.mealprice) print(\"Total Amount Due:\", self.roomrent + self.mealprice) obj = Customer() obj.getCustomer() obj.getroom() obj.getmeals() obj.displaybill()Question 3: Write a Payroll Information System program.
class employee(object): def __init__(self): self.eno = 0 self.name = \'\' self.designation = \'\' self.address = \'\' self.phonenumber = 0 def getdata(self): self.eno = int(input(\"Enter Employee Number: \")) self.name = input(\"Enter Employee Name: \") self.designation = input(\"Enter Employee Designation: \") self.address = input(\"Enter Employee Address: \") self.phonenumber = int(input(\"Enter Employee Phone Number: \")) def putdata(self): print(\"Employee Number:\", self.eno) print(\"Employee Name:\", self.name) print(\"Employee Designation:\", self.designation) print(\"Employee Address:\", self.address) print(\"Employee Phone Number:\", self.phonenumber) class salary(employee): def __init__(self): super(salary, self).__init__() self.basic = 0 self.DA = 0 self.HRA = 0 self.Gross = 0 self.PF = 0 self.tax = 0 self.netpay = 0 def getdatal(self): self.getdata() self.basic = float(input(\"Enter the basic pay: \")) self.DA = float(input(\"Enter the DA: \")) self.HRA = float(input(\"Enter the HRA: \")) self.PF = float(input(\"Enter the PF: \")) def calculate(self): self.Gross = self.basic + self.DA + self.HRA if self.Gross < 100000: self.tax = 0 elif self.Gross < 500000: self.tax = self.Gross * 0.10 elif self.Gross < 1000000: self.tax = self.Gross * 0.15 else: self.tax = self.Gross * 0.20 self.netpay = self.Gross - self.PF - self.tax def display(self): self.putdata() print(\"Gross Income:\", self.Gross) print(\"Tax:\", self.tax) print(\"Net Income:\", self.netpay) salaryobj = salary() num = int(input(\"Enter no. of employees: \")) for i in range(0, num): salaryobj.getdatal() salaryobj.calculate() salaryobj.display()Question 4: Employee and Payroll class with leave functionality.
class Employee(object): def __init__(self): self.eno = 0 self.name = \"\" def Getdata(self): self.eno = int(input(\"Enter the Employee no: \")) self.name = input(\"Enter the Employee Name: \") def Printdata(self): print(\"Employee Number:\", self.eno) print(\"Employee Name:\", self.name) class payroll(Employee): def __init__(self): super(payroll, self).__init__() self.salary = 0 def Inputdata(self): self.Getdata() self.salary = float(input(\"Enter the salary: \")) def Outdata(self): self.Printdata() print(\"Salary is:\", self.salary) class leave(payroll): def __init__(self): super(leave, self).__init__() self.Noofdays = 0 def acceptdata(self): self.Inputdata() self.Noofdays = int(input(\"Enter leave days: \")) def showdata(self): self.Outdata() print(\"No. of leave days:\", self.Noofdays) leaveobj = leave() leaveobj.acceptdata() leaveobj.showdata()Question 5: What output will be generated when the following Python code is executed?
def changeList(): L = [] LI = [] L2 = [] for i in range(10, 1, -2): LI.append(i) for i in range(len(LI)): L2.append(LI[i] + L[i]) print(L2) changeList()Output: [11, 10, 9, 8, 7, 4]