Wednesday, December 2, 2026

Python Programming -Unit III

24MCST21 Python Programming - Unit III
SUBJECT CODE: 24MCST21

PYTHON PROGRAMMING

School of Computer Science

UNIT – III

Modules, Packages and Classes

1. Modules in Python

Definition: A module is a Python file containing functions, variables and classes that can be reused in another Python program. A Python module has the .py extension.

Advantages of Modules

  • Code reusability.
  • Reduces code repetition.
  • Organizes large programs.
  • Easy maintenance and debugging.

Example: Creating a Module

Step 1: Create a file named calculator.py.

def add(a, b):
    return a + b

def sub(a, b):
    return a - b

Step 2: Create another file named main.py.

import calculator

print(calculator.add(10, 20))
print(calculator.sub(20, 5))
Output:
30 15

2. Packages in Python

Definition: A package is a collection of related Python modules organized inside a directory. It helps organize large applications into smaller components.

Package Structure

MyProject/
│
├── main.py
│
└── college/
    ├── __init__.py
    ├── student.py
    └── teacher.py

student.py

def student_details():
    print("Student Name: Arun")

teacher.py

def teacher_details():
    print("Teacher Name: Kumar")

main.py

from college import student, teacher

student.student_details()
teacher.teacher_details()
Student Name: Arun Teacher Name: Kumar

Difference Between Module and Package

ModulePackage
A single Python file.A directory containing related modules.
Has .py extension.Usually contains __init__.py.
Organizes individual code.Organizes multiple modules.
Example: calculator.pyExample: college package

3. Standalone Programs

Definition: A standalone program is a Python program that can execute independently without being imported by another program.

Example

print("Welcome to Python Programming")

a = 10
b = 20

total = a + b

print("Total:", total)
Welcome to Python Programming Total: 30

This program can run directly using the Python interpreter.

4. Command Line Arguments

Definition: Command line arguments are values passed to a Python program during execution through the command prompt or terminal.

Python provides the sys.argv list to access command line arguments.

Example

import sys

print("Program Name:", sys.argv[0])
print("First Argument:", sys.argv[1])
print("Second Argument:", sys.argv[2])

Execution in Terminal

python main.py Arun 25
Program Name: main.py First Argument: Arun Second Argument: 25

Important Points

  • sys.argv[0] represents the program name.
  • sys.argv[1] represents the first argument.
  • sys.argv[2] represents the second argument.
  • Command line arguments are received as strings.

5. Modules and the Import Statement

The import statement is used to access functions, variables and classes from another module.

1. Import Complete Module

import math

print(math.sqrt(25))
5.0

2. Import Specific Function

from math import sqrt

print(sqrt(36))
6.0

3. Import with Alias

import math as m

print(m.factorial(5))
120

4. Import Multiple Functions

from math import sqrt, pow

print(sqrt(49))
print(pow(2, 3))
7.0 8.0

6. Python Standard Library

Definition: The Python Standard Library is a collection of ready-made modules that provide functions for performing different programming tasks.
ModulePurpose
mathMathematical operations
randomGenerate random numbers
datetimeWork with dates and time
osInteract with operating system
sysAccess system information
calendarDisplay calendar
statisticsStatistical calculations
jsonWork with JSON data

Example 1: Math Module

import math

print(math.sqrt(64))
print(math.factorial(5))
8.0 120

Example 2: Random Module

import random

number = random.randint(1, 10)

print("Random Number:", number)
Output changes each time the program runs.

Example 3: DateTime Module

import datetime

today = datetime.date.today()

print("Today's Date:", today)

7. Objects and Classes

What is a Class?

A class is a blueprint or template used to create objects. It defines the attributes and methods of an object.

What is an Object?

An object is an instance of a class. It represents a real-world entity with data and behaviour.

Real-World Example: Student

ConceptExample
ClassStudent
ObjectsArun, Priya, Kumar
AttributesName, Age, Department
MethodsDisplay Details, Calculate Marks

Define a Class with class

class Student:

    def display(self):
        print("Welcome to Python")

s1 = Student()

s1.display()
Welcome to Python

Explanation

  • class Student creates a class.
  • display() is a method.
  • self refers to the current object.
  • s1 = Student() creates an object.
  • s1.display() calls the method.

8. Inheritance

Definition: Inheritance is an object-oriented programming concept in which one class acquires the properties and methods of another class.
  • Parent Class: The class that provides properties.
  • Child Class: The class that receives properties.

Example

class Parent:

    def display(self):
        print("This is Parent Class")

class Child(Parent):
    pass

obj = Child()

obj.display()
This is Parent Class

Types of Inheritance

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multilevel Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

9. Override a Method

Method overriding occurs when a child class defines a method with the same name as a method in its parent class. The child class provides its own implementation.

Example

class Parent:

    def display(self):
        print("Parent Method")

class Child(Parent):

    def display(self):
        print("Child Method")

obj = Child()

obj.display()
Child Method

The child class overrides the display() method of the parent class.

10. Add a Method

A child class can have additional methods that are not available in its parent class.

Example

class Student:

    def display(self):
        print("Student Details")

class Result(Student):

    def calculate(self):
        print("Result Calculated")

obj = Result()

obj.display()
obj.calculate()
Student Details Result Calculated

11. Get Help from Parent with super()

The super() function is used to access methods and constructors of the parent class from the child class.

Example

class Parent:

    def display(self):
        print("Parent Class Method")

class Child(Parent):

    def display(self):
        super().display()
        print("Child Class Method")

obj = Child()

obj.display()
Parent Class Method Child Class Method

Explanation

  • super() accesses the parent class implementation.
  • super().display() calls the parent method.
  • The child class also executes its own method.

12. In Self Defense – Understanding self

self represents the current object of a class. It allows each object to access its own attributes and methods.

Example

class Student:

    def set_details(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        print("Name:", self.name)
        print("Age:", self.age)

s1 = Student()

s1.set_details("Arun", 20)
s1.display()
Name: Arun Age: 20

Important Points

  • self refers to the current object.
  • It accesses instance variables.
  • It is written as the first parameter of instance methods.
  • Python automatically passes the object when an instance method is called.

13. Get and Set Attribute Values with Properties

Properties are used to access and modify object attributes in a controlled manner. Python provides the @property decorator to create getter and setter methods.
  • Getter: Retrieves an attribute value.
  • Setter: Changes an attribute value.

Example

class Student:

    def __init__(self):
        self._name = ""

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

s1 = Student()

s1.name = "Arun"

print(s1.name)
Arun

14. Name Mangling for Privacy

Name mangling is a technique used in Python to make direct access to certain class attributes more difficult. It is performed by adding two underscores before an attribute name.

Example

class Student:

    def __init__(self):
        self.__marks = 90

    def display(self):
        print("Marks:", self.__marks)

s1 = Student()

s1.display()
Marks: 90
Important: Name mangling does not provide complete security or true private access. It mainly helps avoid accidental access and naming conflicts. Internally, __marks is stored using a name similar to _Student__marks.

15. Method Types

Python classes support three major method types.

1. Instance Method

An instance method works with individual object data and uses self.

class Student:

    def display(self):
        print("Instance Method")

s = Student()
s.display()
Instance Method

2. Class Method

A class method works with class-level data and uses cls. It is defined using @classmethod.

class Student:

    college = "NSCAS"

    @classmethod
    def display(cls):
        print(cls.college)

Student.display()
NSCAS

3. Static Method

A static method does not require self or cls. It is defined using @staticmethod.

class Calculator:

    @staticmethod
    def add(a, b):
        print(a + b)

Calculator.add(10, 20)
30

Comparison of Method Types

Instance MethodClass MethodStatic Method
Uses selfUses clsNo self or cls
Works with object dataWorks with class dataGeneral utility
No decorator required@classmethod@staticmethod

16. Duck Typing

Duck typing is a programming concept in which the type or class of an object is less important than the methods or behaviour it supports.

Principle: If it behaves like a duck, it can be treated like a duck.

Example

class Dog:

    def sound(self):
        print("Dog Barks")

class Cat:

    def sound(self):
        print("Cat Meows")

def make_sound(animal):
    animal.sound()

d = Dog()
c = Cat()

make_sound(d)
make_sound(c)
Dog Barks Cat Meows

The make_sound() function works with both Dog and Cat objects because both provide the sound() method.

17. Special Methods

Special methods are predefined methods in Python that begin and end with double underscores. They are also called Magic Methods or Dunder Methods.

Important Special Methods

MethodPurpose
__init__()Initializes an object
__str__()Returns a readable string
__len__()Returns object length
__add__()Defines addition
__eq__()Defines equality comparison
__del__()Called when an object is finalized

Example: __init__() and __str__()

class Student:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

s1 = Student("Arun")

print(s1)
Arun
  • __init__() initializes the object.
  • __str__() defines the readable string representation.
  • print(s1) automatically calls __str__().

18. Composition

Composition is an object-oriented programming concept in which one class contains an object of another class. It represents a "Has-A" relationship.

Real-World Examples

  • A coll

No comments:

Post a Comment

Python Programming -Unit III

24MCST21 Python Programming - Unit III SUBJECT CODE: 24MCST21 PYTHON PROGRAMMING School of Computer Science ...