Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How will you compare modules, classes and namespaces in Python?
Python allows you to save definitions to a file and use them in scripts or interactive interpreter sessions. Understanding how modules, classes, and namespaces work together is essential for organizing and structuring Python code effectively.
What are Modules?
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. Modules help organize code by grouping related functions and classes together.
Creating a Simple Module
Let's create a module called calculator.py ?
# Save this as calculator.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
PI = 3.14159
Using the Module
Now we can import and use this module ?
# Simulate importing our calculator module
def add(x, y):
return x + y
def subtract(x, y):
return x - y
PI = 3.14159
# Using the functions
result1 = add(10, 5)
result2 = subtract(10, 5)
print(f"Addition: {result1}")
print(f"Subtraction: {result2}")
print(f"PI value: {PI}")
Addition: 15 Subtraction: 5 PI value: 3.14159
What are Classes?
A class is a blueprint for creating objects. Classes encapsulate data (attributes) and functions (methods) that operate on that data.
Example
Here's a simple class definition ?
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
return f"Name: {self.name}, Age: {self.age}"
# Creating objects
student1 = Student("Alice", 20)
student2 = Student("Bob", 22)
print(student1.display_info())
print(student2.display_info())
Name: Alice, Age: 20 Name: Bob, Age: 22
What are Namespaces?
A namespace is a mapping from names to objects. It's a way to implement scope in Python. There are four types of namespaces ?
Built-in − Contains built-in functions and exceptions
Global − Module-level names
Enclosing − Names in enclosing functions
Local − Names inside functions
Built-in Namespace Example
Built-in names are always available ?
# These are built-in functions
data = [1, 2, 3, 4, 5]
print(f"Length: {len(data)}")
print(f"Maximum: {max(data)}")
print(f"Type: {type(data)}")
Length: 5 Maximum: 5 Type: <class 'list'>
Global vs Local Namespace
Variables can exist in different scopes ?
# Global variable
count = 10
def increment():
global count
count = count + 1
local_var = 5 # Local variable
print(f"Local variable: {local_var}")
print(f"Global count inside function: {count}")
print(f"Global count before function: {count}")
increment()
print(f"Global count after function: {count}")
Global count before function: 10 Local variable: 5 Global count inside function: 11 Global count after function: 11
Comparison Summary
| Concept | Purpose | Scope | Example |
|---|---|---|---|
| Module | Code organization | File-level | import math |
| Class | Object blueprint | Class definition | class Car: |
| Namespace | Name resolution | Variable scope | Local, Global, Built-in |
How They Work Together
Here's how modules, classes, and namespaces interact ?
# This would be in a module file
class Calculator:
"""A simple calculator class"""
def __init__(self):
self.history = []
def add(self, x, y):
result = x + y
self.history.append(f"{x} + {y} = {result}")
return result
# Using the class
calc = Calculator()
result = calc.add(15, 25)
print(f"Result: {result}")
print(f"History: {calc.history}")
# Namespace demonstration
print(f"Class name: {Calculator.__name__}")
print(f"Method names: {[method for method in dir(calc) if not method.startswith('_')]}")
Result: 40 History: ['15 + 25 = 40'] Class name: Calculator Method names: ['add', 'history']
Conclusion
Modules organize code into files, classes create object blueprints, and namespaces manage variable scope. Together, they provide Python's powerful code organization and encapsulation capabilities, enabling you to write maintainable and structured programs.
