3.
Discuss the concept of object oriented programming in python and how can we create
and manipulate class and object?
Ans. Object-Oriented Programming (OOP) is a programming paradigm (a style of coding)
that relies on the concept of classes and objects. Instead of writing logic based strictly on
functions and actions (Procedural Programming), OOP allows you to structure your program
by bundling related properties and behaviours into individual objects. It models the code
after real-world things.
1. The Building Blocks: Class and Object: The easiest way to understand this is the Blueprint
vs. House analogy.
Class (The Blueprint): This is the logical template. It defines what data an object
should have and what it should do. It doesn't contain actual data yet.
Object (The House): This is the actual instance created from the blueprint. It
occupies memory and holds specific data.
Example:
Class: Dog (Defines that dogs have a breed and colour, and can bark).
Object: my_dog (A specific Golden Retriever named "Buddy").
2. The Syntax: To create a class in Python, use the class keyword.
Class Dog:
# The Constructor: Initializes the object
def __init__(self, name, breed):
[Link] = name # Attribute (Data)
[Link] = breed # Attribute (Data)
# Method (Behavior)
def bark(self):
return f"{[Link]} says Woof!"
# Creating an Object (Instantiation)
pet1 = Dog("Buddy", "Golden Retriever")
print([Link]) # Output: Buddy
print([Link]()) # Output: Buddy says Woof!
3. The Four Pillars of OOP
OOP is defined by four major principles that help organize complex code.
A. Encapsulation: Bundling data and methods together and restricting direct access.
In Python, we act as if variables are private to protect them from being messed up by
outside code.
Analogy: A capsule pill. The medicine (data) is safe inside the coating; you swallow
the whole pill rather than touching the powder directly.
B. Abstraction: Hiding complex implementation details and showing only the necessary
features.
You don't need to know how the engine works to drive a car; you just use the
steering wheel and pedals.
In Python, we use "Abstract Classes" to define a template that forces other classes to
implement specific methods.
C. Inheritance: Creating new classes based on existing ones.
This promotes code reusability. If you have a class Animal, you can create a child
class Cat that inherits all traits of Animal but adds its own unique traits (like meow).
Syntax: class Cat(Animal):
D. Polymorphism: The ability of different objects to respond to the same function call in
their own way.
"Poly" (many) + "Morphism" (forms).
If you have a function make_sound(), a Dog object will "Bark" and a Cat object will
"Meow". The function name is the same, but the result differs based on the object.
Creating and manipulating classes and objects in Python is a straightforward process
involving defining the structure (the class) and then using that structure to create specific
instances (the objects).
1. Creating a Class: To create a class, we use the class keyword. Inside the class, we define
attributes (data) and methods (functions).
class Car:
# 1. The Constructor (Initializer)
# This runs automatically when you create a new object.
def __init__(self, brand, color):
[Link] = brand # Attribute: specific to the object
[Link] = color # Attribute: specific to the object
# 2. A Method (Behavior)
# This is a function that belongs to the class.
def start_engine(self):
print(f"The {[Link]} {[Link]} is starting... Vroom!")
# 3. Another Method
def repaint(self, new_color):
print(f"Changing color from {[Link]} to {new_color}")
[Link] = new_color
2. Creating an Object (Instantiation): Once the class is defined, you can create "instances"
(objects) of that class. You can create as many as you want.
# Creating Object 1
my_car = Car("Toyota", "Red")
# Creating Object 2
neighbor_car = Car("Honda", "Blue")
At this point, my_car and neighbor_car are two separate objects in memory.
3. Manipulating the Object: "Manipulating" means accessing data, changing data, or using
the object's behaviours.
A. Accessing Attributes: You can view the data stored inside an object using dot notation (.).
print(my_car.brand) # Output: Toyota
print(neighbor_car.color) # Output: Blue
B. Calling Methods: You can trigger the actions defined in the class.
my_car.start_engine()
# Output: The Red Toyota is starting... Vroom!
C. Modifying Attributes: You can change the data inside an object either directly or through
a method.
my_car.color = "Black"
print(my_car.color) # Output: Black
4. Advanced Manipulation (Dynamic Changes): Python is very flexible. You can add or
delete attributes of an object even after it has been created, without changing the original
class code.
A. Adding a New Property dynamically: You can add a property to my_car that
neighbor_car does not have.
my_car.speed = 100
print(my_car.speed) # Output: 100
# print(neighbor_car.speed) -> This would cause an Error because it
doesn't exist for this object.
B. Deleting Properties or Objects: You can use the del keyword to remove data.
# Deleting a specific attribute
del my_car.speed
# Deleting the entire object from memory
del my_car
4. What are different ways to import a module? Explain each method with example.
Ans. In Python, there are several ways to import modules depending on whether you want
to use the whole module, just a specific part of it, or if you want to give it a shorter
nickname. Here are the four most common ways to import a module, using Python's built-in
math module as an example.
1. Standard Import (import ...): This is the most common and safest way. It imports the
entire module, but keeps all the functions inside the module's "namespace."
import math
# You must use 'math.' to access the function
result = [Link](25)
print(result) # Output: 5.0
2. Import with Aliasing (import ... as ...): This allows you to import the whole module but
gives it a temporary, shorter name (an alias). This is standard practice for popular libraries
like generic data science tools (e.g., import pandas as pd).
import math as m # 'm' is now the nickname for 'math'
# You can use the short name 'm'
result = [Link](5)
print(result) # Output: 120
3. Specific Import (from ... import ...): This imports only the specific function or variable you
need, not the whole module.
from math import pi, sqrt
print(pi) # Output: 3.14159...
print(sqrt(16)) # Output: 4.0
4. Import Everything (from ... import *): This imports every function and variable from the
module directly into your code.
from math import *
# You can use any function from math directly
print(pow(2, 3)) # Output: 8.0
5. What are module and their need?
Ans. In Python, a Module is simply a file containing Python code. This file can define functions,
classes, and variables that you can reference in other Python scripts. If you think of a single
function as a tool (like a hammer), then a module is a toolbox (a container holding the
hammer, screwdriver, and wrench).Technically, any file ending in .py is a module. The file
name becomes the module name.
Types of Modules: There are three categories of modules in Python:
1. Built-in Modules: These come pre-installed with Python (e.g., math, os, random, datetime).
You don't need to install anything; just import them.
2. User-defined Modules: These are the .py files you create yourself.
3. External Modules: These are created by the community (like pandas or numpy) and must be
installed using a package manager like pip.
Here is how you create and use your own module.
Step 1: Create the Module ([Link]) Save this code in a file named [Link].
# [Link]
def add(x, y):
return x + y
def subtract(x, y):
return x - y
pi = 3.14159
Step 2: Use the Module ([Link]) create another file in the same folder and run this code.
# [Link]
import calculator
# Use the functions from the module
result = [Link](10, 5)
print(result) # Output: 15
# Use a variable from the module
print([Link]) # Output: 3.14159