PYTHON PROGRAMMING
School of Computer Science
Modules, Packages and Classes
📚 UNIT III – Contents
1. Modules 2. Packages 3. Standalone Programs 4. Command Line Arguments 5. Modules and Import Statement 6. Python Standard Library 7. Objects and Classes 8. Inheritance 9. Method Overriding 10. Adding a Method 11. Using super() 12. Understanding self 13. Properties – Get and Set 14. Name Mangling 15. Method Types 16. Duck Typing 17. Special Methods 18. Composition 19. Important Questions1. Modules in Python
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))
2. Packages in Python
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()
Difference Between Module and Package
| Module | Package |
|---|---|
| A single Python file. | A directory containing related modules. |
| Has .py extension. | Usually contains __init__.py. |
| Organizes individual code. | Organizes multiple modules. |
| Example: calculator.py | Example: college package |
3. Standalone Programs
Example
print("Welcome to Python Programming")
a = 10
b = 20
total = a + b
print("Total:", total)
This program can run directly using the Python interpreter.
4. Command Line Arguments
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
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))
2. Import Specific Function
from math import sqrt
print(sqrt(36))
3. Import with Alias
import math as m
print(m.factorial(5))
4. Import Multiple Functions
from math import sqrt, pow
print(sqrt(49))
print(pow(2, 3))
6. Python Standard Library
| Module | Purpose |
|---|---|
| math | Mathematical operations |
| random | Generate random numbers |
| datetime | Work with dates and time |
| os | Interact with operating system |
| sys | Access system information |
| calendar | Display calendar |
| statistics | Statistical calculations |
| json | Work with JSON data |
Example 1: Math Module
import math
print(math.sqrt(64))
print(math.factorial(5))
Example 2: Random Module
import random
number = random.randint(1, 10)
print("Random Number:", number)
Example 3: DateTime Module
import datetime
today = datetime.date.today()
print("Today's Date:", today)
7. Objects and Classes
What is a Class?
What is an Object?
Real-World Example: Student
| Concept | Example |
|---|---|
| Class | Student |
| Objects | Arun, Priya, Kumar |
| Attributes | Name, Age, Department |
| Methods | Display Details, Calculate Marks |
Define a Class with class
class Student:
def display(self):
print("Welcome to Python")
s1 = Student()
s1.display()
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
- 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()
Types of Inheritance
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
9. Override a Method
Example
class Parent:
def display(self):
print("Parent Method")
class Child(Parent):
def display(self):
print("Child Method")
obj = Child()
obj.display()
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()
11. Get Help from Parent with super()
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()
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
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()
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
- 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)
14. Name Mangling for Privacy
Example
class Student:
def __init__(self):
self.__marks = 90
def display(self):
print("Marks:", self.__marks)
s1 = Student()
s1.display()
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()
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()
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)
Comparison of Method Types
| Instance Method | Class Method | Static Method |
|---|---|---|
| Uses self | Uses cls | No self or cls |
| Works with object data | Works with class data | General utility |
| No decorator required | @classmethod | @staticmethod |
16. Duck Typing
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)
The make_sound() function works with both Dog and Cat objects because both provide the sound() method.
17. Special Methods
Important Special Methods
| Method | Purpose |
|---|---|
| __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)
- __init__() initializes the object.
- __str__() defines the readable string representation.
- print(s1) automatically calls __str__().
18. Composition
Real-World Examples
- A coll