Module-IV
Syllabus :
Chapter-I :Modules: Random numbers, the time module, the math module, creating
your own modules, Namespaces, Scope and lookup rules, Attributes and the dot
Operator, Three import statement variants. Mutable versus immutable and aliasing
Chapter 2: Object oriented programming: Classes and Objects — The Basics,
Attributes, Adding methods to our class, Instances as arguments and parameters,
Converting an instance to a string, Instances as return values.
Chapter –I
Random Module in Python:
Definition
The random module in Python is a built-in module used to generate random
numbers and perform random operations such as selecting random items,
shuffling lists, and generating random values.
It helps programmers create unpredictable or random results in programs.
Syntax
import random
import is used to include the module in the program.
After importing, we can use different random functions.
Example 1 — random()
Definition
The random() function generates a random floating-point number between 0
and 1.
Program
import random
number = [Link]()
print(number)
Sample Output
0.6734
Explanation
The output is always:
0.0 <= number < 1.0
Every time the program runs, a different value is produced.
Example 2 — randint()
Definition
The randint() function generates a random integer between two specified
numbers.
Syntax
[Link](start, end)
Program
import random
number = [Link](1, 10)
print(number)
Sample Output
7
Explanation
Generates a random number from 1 to 10
Both 1 and 10 are included.
Example 3 — choice()
Definition
The choice() function selects a random element from a list, tuple, or string.
Program
import random
fruits = ["Apple", "Banana", "Orange", "Mango"]
item = [Link](fruits)
print(item)
Sample Output
Mango
Explanation
One item is selected randomly from the list.
Example 4 — shuffle()
Definition
The shuffle() function randomly changes the order of elements in a list.
Program
import random
numbers = [1, 2, 3, 4, 5]
[Link](numbers)
print(numbers)
Sample Output
[4, 1, 5, 2, 3]
Explanation
The list elements are rearranged randomly.
Common Program using Random Module in Python :
# Random integer
num = [Link](1,10)
print("Random Integer :", num)
# Random floating value
f = [Link]()
print("Random Float :", f)
# Random choice from list
colors = ["Red","Blue","Green","Yellow"]
c = [Link](colors)
print("Random Color :", c)
# Random OTP generation
otp = [Link](1000,9999)
print("Generated OTP :", otp)
# Shuffle list elements
numbers = [1,2,3,4,5]
[Link](numbers)
print("Shuffled List :", numbers)
Sample Output :
Random Integer : 7
Random Float : 0.458923
Random Color : Blue
Generated OTP : 5831
Shuffled List : [4, 1, 5, 2, 3]
Repeatability and Testing in Random Module :
Definition
In Python, random numbers are usually different every time a program runs.
But during testing, programmers may want the program to produce the same
random numbers [Link] is called repeatability.
Repeatability helps in:
Testing programs
Finding errors easily
Debugging programs
Getting predictable results
This is done using: [Link]() from the Python Standard Library random module.
What is seed()?
Definition
The seed() function initializes the random number generator with a fixed
value.
If the same seed value is used, Python generates the same random numbers
every time.
Syntax
[Link](value)
Example Without seed()
import random
print([Link](1, 10))
print([Link](1, 10))
Output (changes every run)
First Run
4
8
Second Run
1
9
Example With seed()
import random
[Link](5)
print([Link](1, 10))
print([Link](1, 10))
Output
10
5
If you run the program again, the output will still be:
10
5
Explanation
[Link](5)
Sets the starting point for random number generation.
Python follows the same sequence of numbers each time.
So the program becomes repeatable.
Why is Repeatability Important?
1. Testing Programs
Programmers can test whether the output is correct.
2. Debugging
Errors can be reproduced easily.
3. Comparing Results
Useful in games, simulations, and scientific programs.
Real-Life Example
Dice Testing Program
import random
[Link](2)
for i in range(5):
print([Link](1, 6))
Output
1
1
1
3
2
Every time the program runs, the same numbers appear.
Important Note
Without seed() → Different outputs every run
With seed() → Same outputs every run
Picking Balls from a Bag
Definition
Selecting a ball from a bag without knowing which ball will come out is called
a random event.
Example Program
import random
balls = ["Red", "Blue", "Green", "Yellow"]
picked_ball = [Link](balls)
print("Picked Ball:", picked_ball)
Sample Output
Picked Ball: Green
Explanation
choice() randomly selects one ball from the list.
Every execution may produce a different color.
The Time Module in Python :
Definition
The time module in Python is a built-in module used to perform time-related
operations such as:
Getting the current time
Pausing program execution
Displaying date and time
Formatting time and date
To use the module, we first import it. Importing the Time Module
import time
1. time() Function
Definition
The time() function returns the current time in seconds from January 1, 1970
(Unix Epoch).
Example Program
import time
current_time = [Link]()
print(current_time)
Sample Output
1715498200.45
Explanation
[Link]() returns the total number of seconds.
The value is stored in current_time.
The output changes every second.
2. sleep() Function
Definition
The sleep() function pauses the execution of a program for a specified number
of seconds.
Example Program
import time
print("Program Started")
[Link](3)
print("Program Ended")
Output
Program Started
(waits for 3 seconds)
Program Ended
Explanation
sleep(3) stops the program for 3 seconds.
After the delay, the next statement executes.
3. ctime() Function
Definition
The ctime() function converts system time into a readable date and time format.
Example Program
import time
print([Link]())
Sample Output
Tue May 12 10:30:15 2026
Explanation
Displays:
Day
Month
Date
Time
Year
in readable form.
4. localtime() Function
Definition
The localtime() function returns the current local time as a structured object.
Example Program
import time
local = [Link]()
print(local)
Sample Output
time.struct_time(tm_year=2026, tm_mon=5, tm_mday=12,
tm_hour=10, tm_min=30, tm_sec=20, ...)
Explanation
It provides detailed information such as:
Year
Month
Day
Hour
Minute
Second
5. strftime() Function
Definition
The strftime() function formats date and time according to the specified format.
Example Program
import time
formatted = [Link]("%d-%m-%Y")
print(formatted)
Sample Output
12-05-2026
Explanation
Format symbols:
Symbol Meaning
%d Day
%m Month
%Y Year
The function converts the current date into the required format.
Another Example of strftime()
import time
formatted = [Link]("%H:%M:%S")
print(formatted)
Sample Output
10:45:20
Explanation
Symbol Meaning
%H Hour
%M Minute
%S Second
Real-Time Example — Stopwatch Delay
import time
print("Start")
[Link](5)
print("5 Seconds Completed")
Explanation
The program waits for 5 seconds before printing the second message.
Useful in timers, games, and automation programs.
Common Program using Time Module:
import time
# Current time in seconds
print("Current Time :", [Link]())
# Current date and time
print("Current Date & Time :", [Link]())
# Local time
print("Local Time :", [Link]())
# Delay execution for 3 seconds
print("Wait for 3 seconds...")
[Link](3)
print("Program Resumed")
OUTPUT :
Current Time : 1779583200.56
Current Date & Time : Sat May 23 18:45:20 2026
Local Time : time.struct_time(tm_year=2026,
tm_mon=5, tm_mday=23, tm_hour=18, tm_min=45, tm_sec=20)
Wait for 3 seconds...
Program Resumed
The Math Module in Python :
Definition
The math module in Python is a built-in module used to perform mathematical
calculations.
It provides functions for:
Square roots
Powers
Factorials
Trigonometric operations
Logarithms
Mathematical constants
To use the module, we first import [Link] the Math Module : import math
Common Functions in Math Module
Function Purpose
sqrt() Finds square root
pow() Finds power
factorial() Finds factorial
ceil() Rounds upward
floor() Rounds downward
fabs() Finds absolute value
sin(), cos(), tan() Trigonometric functions
log() Finds logarithm
1. sqrt() Function
Definition
The sqrt() function returns the square root of a number.
Example Program
import math
result = [Link](25)
print(result)
Output
5.0
Explanation
The square root of 25 is 5.
Output is returned as a floating-point value.
2. pow() Function
Definition
The pow() function returns the value of a number raised to a power.
Syntax
[Link](base, exponent)
Example Program
import math
result = [Link](2, 3)
print(result)
Output
8.0
3. factorial() Function
Definition
The factorial() function returns the factorial of a number.
Example Program
import math
result = [Link](5)
print(result)
Output
120
Explanation
5 × 4 × 3 × 2 × 1 = 120
4. ceil() Function
Definition
The ceil() function rounds a number upward to the nearest integer.
Example Program
import math
result = [Link](4.2)
print(result)
Output
5
Explanation
4.2 is rounded upward to 5.
5. floor() Function
Definition
The floor() function rounds a number downward to the nearest integer.
Example Program
import math
result = [Link](4.9)
print(result)
Output
4
Explanation
4.9 is rounded downward to 4.
6. fabs() Function
Definition
The fabs() function returns the absolute positive value of a number.
Example Program
import math
result = [Link](-15)
print(result)
Output
15.0
Explanation
Negative sign is removed.
7. Trigonometric Functions
Definition
The sin(), cos(), and tan() functions are used for trigonometric calculations.
Example Program
import math
result = [Link](0)
print(result)
Output
0.0
Explanation
The sine value of 0 is 0.
8. log() Function
Definition
The log() function returns the logarithm of a number.
Example Program
import math
result = [Link](10)
print(result)
Sample Output
2.30258509299
Explanation
Returns the natural logarithm of 10.
Mathematical Constants
Constant Meaning
[Link] Value of π
math.e Euler’s number
Example Program
import math
print([Link])
print(math.e)
Output
3.141592653589793
2.718281828459045
Real-Time Example :
import math
radius = 5
area = [Link] * [Link](radius, 2)
print(area)
Output
78.53981633974483
Explanation
Radius = 5
Formula used:
π × r²
Calculates area of the circle.
Common program using Math module:
import math
# Square root
print("Square Root of 25 =", [Link](25))
# Power
print("2 power 3 =", [Link](2,3))
# Ceiling value
print("Ceil of 4.2 =", [Link](4.2))
# Floor value
print("Floor of 4.8 =", [Link](4.8))
# Absolute value
print("Absolute value of -10 =", [Link](-10))
# Value of pi
print("Value of PI =", [Link])
OUTPUT:
Square Root of 25 = 5.0
2 power 3 = 8.0
Ceil of 4.2 = 5
Floor of 4.8 = 4
Absolute value of -10 = 10.0
Value of PI = 3.141592653589793
Creating Your Own Modules in Python :
Definition
A module in Python is a file containing Python code such as:
functions
variables
classes
Creating your own module means writing code in one Python file and reusing it in
another Python program using import.
What is a Module?
A module is simply a Python file with .py extension.
Example: [Link] This file itself becomes a module.
Step 1 — Create Your Own Module
Create a file named: [Link]
Write the following code inside it:
def add(a, b):
return a + b
def multiply(a, b):
return a * b
Explanation
This module contains two functions:
add() → adds two numbers
multiply() → multiplies two numbers
Step 2 — Create Another Python File
Create another file named: [Link]
Write:
import calculator
print([Link](5, 3))
print([Link](5, 3))
Output
8
15
Step-by-Step Explanation
Importing the Module
import calculator
Imports the module [Link]
Now all functions inside it can be used.
Calling Functions
[Link](5, 3)
calls the add() function from the module.
Another Method — Import Specific Function
from calculator import add
print(add(10, 2))
Output
12
Using Variables in Modules
Module File
# [Link]
name = "Python"
Main Program
import mymodule
print([Link])
Output
Python
Real-Life Example :
School Management System Using Modules in Python :
Project files:
[Link]
[Link]
[Link]
[Link]
[Link]
1. [Link]
Stores Student Details
# [Link]
student_name = "Ravi"
student_id = 101
def display_student():
print("Student Name:", student_name)
print("Student ID:", student_id)
2. [Link]
Stores Fee Information
# [Link]
fees_paid = 25000
total_fees = 50000
def display_fees():
print("Fees Paid:", fees_paid)
print("Total Fees:", total_fees)
print("Balance Fees:", total_fees - fees_paid)
3. [Link]
Stores Marks
# [Link]
python_mark = 85
java_mark = 78
dbms_mark = 90
def display_marks():
print("Python Mark:", python_mark)
print("Java Mark:", java_mark)
print("DBMS Mark:", dbms_mark)
total = python_mark + java_mark + dbms_mark
print("Total Marks:", total)
4. [Link]
Stores Attendance Details
# [Link]
total_days = 100
present_days = 92
def display_attendance():
print("Total Working Days:", total_days)
print("Present Days:", present_days)
percentage = (present_days / total_days) * 100
print("Attendance Percentage:", percentage)
5. [Link]
Main Program Using All Modules
# [Link]
import student
import fees
import marks
import attendance
print("----- STUDENT DETAILS -----")
student.display_student()
print("\n----- FEES DETAILS -----")
fees.display_fees()
print("\n----- MARK DETAILS -----")
marks.display_marks()
print("\n----- ATTENDANCE DETAILS -----")
attendance.display_attendance()
Output
----- STUDENT DETAILS -----
Student Name: Ravi
Student ID: 101
----- FEES DETAILS -----
Fees Paid: 25000
Total Fees: 50000
Balance Fees: 25000
----- MARK DETAILS -----
Python Mark: 85
Java Mark: 78
DBMS Mark: 90
Total Marks: 253
----- ATTENDANCE DETAILS -----
Total Working Days: 100
Present Days: 92
Attendance Percentage: 92.0
Namespaces in Python :
Definition
A namespace is a collection of identifiers (names) and their corresponding
objects.
Namespaces help Python organize variables, functions, and modules so that
the same name can be used in different places without conflict.
In simple words: Namespace = a container that stores names and values.
Example of Namespace
x = 10
Python stores: x → 10 inside a namespace.
Why Namespaces Are Important?
Namespaces avoid naming [Link] modules or functions can use
the same variable name without affecting each other.
Example Using Two Modules
[Link]
# [Link]
question = "What is the meaning of Life, the Universe, and Everything?"
answer = 42
[Link]
# [Link]
question = "What is your quest?"
answer = "To seek the holy grail."
Main Program
import module1
import module2
print([Link])
print([Link])
print([Link])
print([Link])
Output
What is the meaning of Life, the Universe, and Everything?
What is your quest?
42
To seek the holy grail.
Explanation
Both modules contain:
question
answer
variables.
But there is no confusion because:
[Link]
[Link]
belong to different namespaces.
Function Namespace Example
def f():
n=7
print("Printing n inside f:", n)
def g():
n = 42
print("Printing n inside g:", n)
n = 11
print("Printing n before calling f:", n)
f()
print("Printing n after calling f:", n)
g()
print("Printing n after calling g:", n)
Output
Printing n before calling f: 11
Printing n inside f: 7
Printing n after calling f: 11
Printing n inside g: 42
Printing n after calling g: 11
Explanation
There are 3 different variables named n.
Location Value
Global namespace 11
Function f() namespace 7
Function g() namespace 42
They do not conflict because each exists in a different namespace.
Scope and Lookup Rules in Python :
Scope in Python :
Scope means the region of a program where a variable can be accessed or
used.
A variable created in one part of a program may or may not be available in
another part depending on its scope. Python uses the LEGB Rule for variable
lookup.
LEGB stands for:
L – Local Scope
E – Enclosing Scope
G – Global Scope
B – Built-in Scope
When Python encounters a variable name, it searches in this order:
Local → Enclosing → Global → Built-in
Local Scope (L) :
A variable declared inside a function belongs to the local [Link] can be
used only inside that function.
Example
def student():
name = "Arun" # Local Variable
print("Inside function :", name)
student()
Output
Inside function : Arun
Explanation
name is created inside student().
Therefore, it is a local variable.
It can be accessed only inside that function.
3. Global Scope (G)
A variable declared outside all functions is called a global variable.
It can be accessed throughout the program.
Example
x = 100 # Global Variable
def display():
print("Inside function :", x)
display()
print("Outside function :", x)
Output
Inside function : 100
Outside function : 100
Explanation
x is created outside the function.
Hence, it belongs to the global scope.
Both inside and outside functions can access it.
4. Enclosing Scope (E)
Enclosing scope occurs in nested functions.
The inner function can access variables of the outer function.
Example
def outer():
msg = "Hello Python" # Enclosing Variable
def inner():
print(msg)
inner()
outer()
Output
Hello Python
Explanation
msg belongs to outer().
inner() is inside outer().
Therefore, msg becomes an enclosing variable for inner().
5. Built-in Scope (B)
Python provides many predefined names and functions called built-in objects.
Examples:
len(), max(), min(), print()
Example
text = "Python"
print(len(text))
Output
6
Explanation
len() is not created by the programmer.
It is already available in Python.
Therefore, it belongs to the built-in scope.
Lookup Rules (Precedence Rules)
Python searches variable names in a fixed [Link] is called scope lookup.
Priority order: Local → Enclosing → Global → Built-in .The innermost
scope gets highest priority.
Example 1 — Built-in Name Hidden
def range(n):
return 123 * n
print(range(10))
Output
1230
Explanation
Normally:
range() is a built-in Python [Link] here we created our own function named
range.
So Python uses: our global function instead of built-in range().Because: Global scope
> Built-in scope
Example 2 — Local vs Global Scope
n = 10
m=3
def f(n):
m=7
return 2 * n + m
print(f(5), n, m)
Output
17 10 3
Step-by-Step Explanation
Global Variables
n = 10
m=3
These belong to global scope.
Function Definition
def f(n):
The parameter n is local to function f.
Local Variable
m=7
This m is local to the function.
Calculation
return 2 * n + m
Uses local values:
n=5
m=7
Calculation:
2 * 5 + 7 = 17
Outside Function
After function execution:
n = 10
m=3
remain unchanged.
So output becomes:
17 10 3
Attributes and the Dot Operator in Python :
Definition of Attributes
Variables and functions defined inside a module are called attributes of the
[Link] can also have attributes.
In simple words:Attributes are data or functions that belong to a module or
object.
Dot Operator (.)
The dot operator is used to access attributes.
Syntax
[Link]
or
[Link]
Example 1 — Module Attributes
[Link]
question = "What is the meaning of Life?"
answer = 42
[Link]
question = "What is your quest?"
answer = "To seek the holy grail."
Main Program
import module1
import module2
print([Link])
print([Link])
Output
What is the meaning of Life?
What is your quest?
Explanation
Both modules contain a variable named:
question
To avoid confusion, we use:
[Link]
[Link]
Here:
module1 and module2 are module names
question is the attribute
. is the dot operator
Example 2 — Function Attribute
[Link]
def remove_at():
print("Item Removed")
Main Program
import seqtools
seqtools.remove_at()
Output
Item Removed
Explanation
seqtools.remove_at
means:
seqtools → module
remove_at → function attribute
Accessed using dot operator.
Object Attributes : Objects also contain attributes.
Example
text = "Python"
print([Link]())
Output
PYTHON
Explanation
text is an object
upper() is its method (attribute)
Accessed using: [Link]()
Three Import Statement Variants in Python :
Definition
The import statement is used to bring modules or functions into the current
namespace so they can be used in a program.
Python provides three common import variants.
Import Entire Module
Syntax
import module_name
Example
import math
x = [Link](10)
print(x)
Output
3.1622776601683795
Explanation
Only the name math is added to the current namespace.
Functions inside the module are accessed using dot operator (.)
Example:
[Link](10)
2. Import Specific Functions
Syntax
from module_name import function_name
Example
from math import cos, sin, sqrt
x = sqrt(10)
print(x)
Output
3.1622776601683795
Explanation
Functions are added directly to the current namespace.
So we can use:
sqrt(10)
instead of: [Link](10)
3. Import Everything
Syntax
from module_name import *
Example
from math import *
x = sqrt(10)
print(x)
Output
3.1622776601683795
Explanation
All functions and variables from math module are imported into current namespace.
Functions can be used directly without qualification.
Import Using Alias (as)
Syntax
import module_name as short_name
Example
import math as m
print([Link])
Output
3.141592653589793
Explanation
math module is imported with shorter name m
Makes typing easier
Mutable vs Immutable and Aliasing in Python :
Mutable Datatypes :
Definition : Mutable objects are objects whose contents can be changed after
creation.
Examples of Mutable Datatypes
List
Dictionary
Set
Example
my_list = [2, 4, 5, 3, 6, 1]
my_list[0] = 9
print(my_list)
Output
[9, 4, 5, 3, 6, 1]
Explanation
Originally:
[2, 4, 5, 3, 6, 1]
After changing first element:
[9, 4, 5, 3, 6, 1]
The list changed successfully.
So lists are mutable.
Immutable Datatypes :
Definition: Immutable objects cannot be changed after creation.
Examples of Immutable Datatypes
String
Tuple
Integer
Float
Example Using Tuple
my_tuple = (2, 5, 3, 1)
my_tuple[0] = 9
Output
TypeError
Explanation
Tuples cannot be modified after creation.
So Python gives: TypeError
Aliasing :
Definition
Aliasing occurs when two variables refer to the same object in memory.
Example
list_one = [1, 2, 3, 4, 6]
list_two = list_one
list_two[-1] = 5
print(list_one)
Output
[1, 2, 3, 4, 5]
Why Did list_one Change?
Because: list_one and list_two both refer to the same list object.
Chapter –II
Object oriented programming: The Basics :
Object-oriented programming:
Python is an object-oriented programming language (OOP).
This means Python provides features that help programmers create programs
using objects and classes.
Object-Oriented Programming began in the 1960s, but it became very popular
during the 1980s when software systems became larger and more complex.
OOP was developed to make programs:
Easier to understand
Easier to manage
Easier to modify and reuse
More organized for large projects
Procedural Programming vs Object-Oriented Programming
1. Procedural Programming
In procedural programming, the main focus is on:
Functions
Procedures
Step-by-step instructions
The data and functions are usually kept separate.
Example
# Procedural Programming Example
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Here:
add() is a function
Data (10, 20) is passed to the function
Focus is mainly on the procedure/function
2. Object-Oriented Programming
In OOP, the focus is on [Link] object contains:
Data (Attributes)
Functions (Methods)
Both are combined together inside a class.
Syntax for Creating a Class :
class ClassName:
def __init__(self):
# attributes
pass
Where:
class → keyword to create class
ClassName → name of the class
__init__() → constructor method
self → refers to current object
Syntax for Creating an Object :
object_name = ClassName()
Real-World Example
Think about a Car.
A car has:
Data / Attributes
Color
Brand
Speed
Functions / Methods
Start()
Stop()
Accelerate()
In OOP, we represent this using a class.
Python OOP Example
class Car:
def __init__(self, brand, color):
[Link] = brand
[Link] = color
def start(self):
print([Link], "car is starting")
def stop(self):
print([Link], "car is stopping")
# Creating Object
car1 = Car("Toyota", "Red")
# Accessing Data
print([Link])
print([Link])
# Calling Methods
[Link]()
[Link]()
Output
Toyota
Red
Toyota car is starting
Toyota car is stopping
Advantages of OOP
1. Reusability
Code can be reused using classes and inheritance.
2. Easy Maintenance
Large programs become easier to update and modify.
3. Better Organization
Data and functions are kept together.
4. Real-World Modeling
Real-world objects can be represented easily.
Examples:
Student
Bank Account
Employee
Car
Mobile Phone
Attributes :
In Object-Oriented Programming (OOP), an attribute is a variable that
belongs to an object or [Link] are used to store data related to an
object.
For example:
A Student object may have attributes like:
o name
o roll_no
o marks
A Car object may have:
o brand
o color
o speed
Types of Attributes in Python
There are mainly two types of attributes:
1. Instance Attribute
2. Class Attribute
1. Instance Attribute
Instance attributes are variables that belong to a specific [Link] object
can have different values.
Example
class Student:
def __init__(self, name, mark):
[Link] = name
[Link] = mark
# Creating objects
s1 = Student("Ravi", 85)
s2 = Student("Priya", 90)
# Accessing attributes
print([Link])
print([Link])
print([Link])
print([Link])
Output
Ravi
85
Priya
90
Explanation
[Link] = name
[Link] = mark
Here:
name and mark are instance attributes
self refers to the current object
So:
[Link] → Ravi
[Link] → Priya
Each object stores its own data.
Real-Time Example
class Mobile:
def __init__(self, brand, price):
[Link] = brand
[Link] = price
m1 = Mobile("Samsung", 25000)
m2 = Mobile("iPhone", 80000)
print([Link], [Link])
print([Link], [Link])
Output
Samsung 25000
iPhone 80000
2. Class Attribute
Class attributes are shared by all objects of the class.
Example
class College:
college_name = "ABC Engineering College"
def __init__(self, student_name):
self.student_name = student_name
s1 = College("Anu")
s2 = College("Kumar")
print(s1.student_name)
print(s1.college_name)
print(s2.student_name)
print(s2.college_name)
Output
Anu
ABC Engineering College
Kumar
ABC Engineering College
Explanation
college_name = "ABC Engineering College"
This is a class attribute.
It is common for all students.
Accessing Attributes Using Dot Operator
Attributes are accessed using the dot (.) operator.
Example
class Person:
def __init__(self, name):
[Link] = name
p = Person("Rahul")
print([Link])
Output
Rahul
Here:
[Link]
p → object
name → attribute
Adding New Attributes Dynamically
Python allows adding attributes dynamically.
Example
class Employee:
pass // Pass means the class is empty.
e1 = Employee()
[Link] = "Arun"
[Link] = 50000
print([Link])
print([Link])
Output
Arun
50000
Adding methods to our class:
In Python, a method is a function defined inside a [Link] describe the
behavior or actions of an object.
Attributes → store data ( Data (attributes) )
Methods → perform actions (Operations (methods)
Ex:
A Car can:
start()
stop()
accelerate()
A Student can:
study()
attend_exam()
Example:
# Define the Point class
class Point:
"""Create a new Point at coordinates x, y"""
# Constructor method
def __init__(self, x=0, y=0):
"""Initialize the point"""
self.x = x
self.y = y
# Method to calculate distance from origin
def distance_from_origin(self):
"""Compute distance from origin"""
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
# Creating objects of Point class
# First point
p = Point(3, 4)
print("Point p")
print("x =", p.x)
print("y =", p.y)
print("Distance from origin =", p.distance_from_origin())
print("--------------------------------")
# Second point
q = Point(5, 12)
print("Point q")
print("x =", q.x)
print("y =", q.y)
print("Distance from origin =", q.distance_from_origin())
print("--------------------------------")
# Third point using default values
r = Point()
print("Point r")
print("x =", r.x)
print("y =", r.y)
print("Distance from origin =", r.distance_from_origin())
OUTPUT:
Point p
x=3
y=4
Distance from origin = 5.0
--------------------------------
Point q
x=5
y = 12
Distance from origin = 13.0
--------------------------------
Point r
x=0
y=0
Distance from origin = 0.0
Explanation of the Program
1. Class Definition
class Point:
Creates a new class called Point.
2. Constructor Method
def __init__(self, x=0, y=0):
__init__() is called automatically when an object is created.
It initializes the object's attributes.
Parameters
self → current object
x=0 → default x-coordinate
y=0 → default y-coordinate
3. Attributes
self.x = x
self.y = y
Stores values inside the object.
4. Method Definition
def distance_from_origin(self):
This method calculates the distance between:
the point (x, y)
and the origin (0, 0)
Instances as arguments and parameters:
In Python OOP, we can:
pass an object (instance) as an argument to a method
receive an object as a parameter inside another method
This allows objects to interact with each other.
What is an Instance?
An instance is an object created from a class.
Example
class Student:
pass
s1 = Student()
Here:
Student → class
s1 → instance/object
Passing an Instance as an Argument :
We can pass one object to another method.
Example: Distance Between Two Points
This is the most common example for instances as parameters.
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
dx = self.x - other.x
dy = self.y - other.y
return [Link](dx**2 + dy**2)
# Create objects
p1 = Point(2, 3)
p2 = Point(5, 7)
# Pass p2 as argument
d = [Link](p2)
print("Distance =", d)
Output
Distance = 5.0
Explanation
Method Definition
def distance(self, other):
self → current object (p1)
other → another object (p2)
Returning Instances from Methods :
Methods can also return objects.
Example
class Number:
def __init__(self, value):
[Link] = value
def add(self, other):
result = [Link] + [Link]
return Number(result)
n1 = Number(10)
n2 = Number(20)
n3 = [Link](n2)
print([Link])
Output
30
Converting an instance to a string :
Converting an Instance to a String in Python
When we create an object and print it directly, Python normally displays:
the class name
memory location of the object
Example:
p = Point(3, 4)
print(p)
Output:
<__main__.Point object at 0x01F9AA10>
This output is not user-friendly. To display objects in a meaningful format, we use:
__str__() method
Example
# Point class with __str__ method
class Point:
"""Create a Point object"""
# Constructor
def __init__(self, x=0, y=0):
self.x = x
self.y = y
# String conversion method
def __str__(self):
return "({0}, {1})".format(self.x, self.y)
# Create objects
p = Point(3, 4)
q = Point(5, 7)
r = Point()
# Print objects
print("Point p =", p)
print("Point q =", q)
print("Point r =", r)
# Using str() function
print(str(p))
print(str(q))
Output
Point p = (3, 4)
Point q = (5, 7)
Point r = (0, 0)
(3, 4)
(5, 7)
Explanation
1. Constructor Method
def __init__(self, x=0, y=0):
Initializes:
x-coordinate
y-coordinate
2. __str__() Method
def __str__(self):
return "({0}, {1})".format(self.x, self.y)
This method:
converts the object into a readable string
is automatically called by:
o print()
o str()
Instances as return values.:
Instances as Return Values in Python OOP
In Python Object-Oriented Programming (OOP), functions and methods can
return objects (instances).This means a function or method can:
1. create a new object
2. return that object
This concept is called Instances as Return Values
Example :
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x}, {self.y})"
def midpoint(p1, p2):
mx = (p1.x + p2.x) / 2
my = (p1.y + p2.y) / 2
return Point(mx, my)
# Creating Point objects
p = Point(3, 4)
q = Point(5, 12)
# Function returns new object
r = midpoint(p, q)
print("First Point :", p)
print("Second Point:", q)
print("Midpoint :", r)
Output
First Point : (3, 4)
Second Point: (5, 12)
Midpoint : (4.0, 8.0)
Explanation
1. Creating the Class
class Point:
This class represents a point with:
x-coordinate
y-coordinate
2. Constructor Method
def __init__(self, x, y):
Initializes the object values.
Example:
p = Point(3, 4)
stores:
x=3
y=4
3. String Method
def __str__(self):
Returns the object as a readable string.
So,
print(p)
displays:
(3, 4)
4. midpoint Function
def midpoint(p1, p2):
takes two Point objects as arguments.
Midpoint Formula
(x1+x2)/2,(y1+y2/2)
5. Midpoint Calculation
mx = (p1.x + p2.x) / 2
my = (p1.y + p2.y) / 2
For:
p = (3,4)
q = (5,12)
Calculation:
mx = (3 + 5)/2 = 4.0
my = (4 + 12)/2 = 8.0
6. Returning New Object
return Point(mx, my) creates and returns a new Point object.
Returned object: Point(4.0, 8.0) This is called:Instances as Return Values
************** --------------------------*********************