A module organizes reusable Python code in a file or package. A class is a blueprint that defines attributes and methods. An object, also called an instance, is a concrete value created from a class and stored in memory. In short: import a module, obtain a class or function from it, and create or receive objects that your program uses.
- Modules organize and expose reusable names.
- Classes define structure and behavior; objects carry actual state.
- Dot notation connects them:
module.Class(),object.attributeandobject.method().
Module vs Class vs Object in Python: The Short Explanation
A module organizes reusable code, a class defines a reusable type or blueprint, and an object is a runtime instance with real values. The examples connect these beginner Python concepts to datetime, pathlib, pandas, pyodbc and openpyxl used in industrial reporting.
Related Search Topics
difference between module class and object in Python · Python class and object examples · Python modules explained for beginners · Python methods and attributes
Python Module, Class and Object Hierarchy
datetime, pathlib, pandasdatetime, Path, DataFrametimestamp, OUTPUT_FOLDER, event_dataMODULE / PACKAGE
├── classes
├── functions
└── variables
│
└── ClassName(arguments) → OBJECT IN MEMORY
Examples:
datetime module → datetime class → timestamp object
pathlib module → Path class → OUTPUT_FOLDER object
pandas package → DataFrame class→ event_data object
Module vs Class vs Object in Python
Module: a reusable code namespace
A module is normally a .py file containing Python code. A package is a directory-based module structure. Modules can expose functions, variables, classes and submodules. Standard-library examples include datetime, pathlib and sys; third-party packages include pandas, pyodbc and openpyxl.
| Module/package | Typical contents used in reporting |
|---|---|
datetime | datetime, date, time, timedelta |
pathlib | Path, PurePath, PureWindowsPath |
sys | exit(), argv, platform |
pandas | DataFrame, Series, read_sql_query() |
pyodbc | connect(), Connection and Cursor objects |
openpyxl | Workbook, worksheets, cells and style classes such as Font, Alignment and PatternFill |
Class: the blueprint
A class describes which data an object may hold and which operations it can perform. Attributes represent state; methods implement behavior. Think of a recipe that can produce many dishes, or a blueprint that can produce many houses.
class ReportJob:
def __init__(self, name, output_folder):
self.name = name # instance attribute
self.output_folder = output_folder
def full_path(self): # instance method
return self.output_folder / self.name
Object: a specific instance
An object is a concrete instance with actual values. Creating it is called instantiation. Two objects from the same class share the defined behavior but can contain different data.
job_a = ReportJob("SQF-02.xlsx", Path(r"D:\SQF_Reports"))
job_b = ReportJob("Daily.xlsx", Path(r"D:\Daily_Reports"))
How Python Modules, Classes and Objects Work Together
- Write or import a module. Python locates the file/package and creates a module namespace.
- Define or obtain a class. The class statement executes during import, or the class is imported directly.
- Create an object. Calling a class normally invokes object construction and initialization.
- Use the object. Read its attributes and call its methods with dot notation.
# 1. Import a class from a module
from pathlib import Path
# 2. Path is the class blueprint
# 3. Calling it creates an object
output_folder = Path(r"D:\SQF_Reports")
# 4. Use attributes and methods
print(output_folder.name)
output_folder.mkdir(parents=True, exist_ok=True)
Want to build industrial Python reports?
Learn SQL extraction, pandas processing, Excel formatting and automated reporting with practical plant-data examples.
4. Detailed Example: datetime
The standard-library datetime module contains a class also named datetime. This identical naming is why imports can initially look confusing.
import datetime
now_a = datetime.datetime.now()
from datetime import datetime
now_b = datetime.now()
print(now_b.year) # attribute
print(now_b.strftime("%Y-%m-%d")) # instance method
print(now_b.isoformat()) # instance method
datetime.now() is a class method that returns a new datetime object. That object contains real values—year, month, day, hour, minute and second—and provides formatting and transformation methods. datetime(2026, 7, 26, 9, 35, 42) creates another object explicitly.
5. Detailed Example: pathlib.Path
pathlib is the module; Path is a class; OUTPUT_FOLDER is an object representing one specific filesystem path. The slash operator works because the class implements operator overloading.
from pathlib import Path
OUTPUT_FOLDER = Path(r"D:\SQF_Reports")
report_file = OUTPUT_FOLDER / "SQF-02.xlsx"
OUTPUT_FOLDER.mkdir(parents=True, exist_ok=True)
print(OUTPUT_FOLDER.exists())
print(OUTPUT_FOLDER.name)
print(report_file.parent)
print(report_file.resolve())
The expression OUTPUT_FOLDER / "SQF-02.xlsx" calls special path behavior such as __truediv__; it does not perform arithmetic division. The result is another Path object.
6. Detailed Example: pandas.DataFrame
pandas is imported using the conventional alias pd. DataFrame is the class used for tabular data. Functions such as pd.read_sql_query() construct and return DataFrame objects.
import pandas as pd
event_data = pd.read_sql_query(query, connection)
print(event_data.shape) # attribute-like tuple: rows, columns
print(event_data.columns) # column labels
print(event_data.dtypes) # data types
print(event_data.empty) # boolean property
clean_data = event_data.copy()
clean_data = clean_data.fillna("")
clean_data.to_excel("SQF-02.xlsx", index=False)
event_data and clean_data are different DataFrame objects. They inherit DataFrame methods such as copy(), fillna(), astype() and to_excel(), while their rows, columns and values form the object state.
7. Complete Import and Usage Flow
from datetime import datetime
from pathlib import Path
import sys
import pandas as pd
import pyodbc
from openpyxl.styles import Font, Alignment, PatternFill
OUTPUT_FOLDER = Path(r"D:\SQF_Reports")
OUTPUT_FOLDER.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now()
connection = pyodbc.connect(connection_string, timeout=15)
event_data = pd.read_sql_query(query, connection)
header_font = Font(bold=True)
alignment = Alignment(horizontal="center", vertical="center")
header_fill = PatternFill(fill_type="solid", fgColor="F4B183")
if event_data.empty:
connection.close()
sys.exit("No data found")
The flow combines several creation patterns. Path(...), Font(...) and Alignment(...) instantiate classes directly. datetime.now(), pyodbc.connect() and pd.read_sql_query() are callable APIs that return objects. In every case, the assigned variable becomes a reference to the returned object.
8. Quick Reference Table
| Import/source | Class or callable | Object variable | Example use |
|---|---|---|---|
datetime | datetime.now() | timestamp | timestamp.strftime(...) |
pathlib | Path | OUTPUT_FOLDER | OUTPUT_FOLDER.mkdir() |
pandas | read_sql_query() → DataFrame | event_data | event_data.to_excel() |
pyodbc | connect() → Connection | connection | connection.cursor() |
openpyxl.styles | Font | header_font | cell.font = header_font |
openpyxl.styles | Alignment | alignment | cell.alignment = alignment |
openpyxl.styles | PatternFill | header_fill | cell.fill = header_fill |
9. Where Modules, Classes and Objects Live in Memory
On storage: Python files and package directories contain source or extension-module code.
During import: Python loads/initializes the module, creates a module object, and normally caches it in sys.modules.
During execution: class objects, functions, and instances such as timestamp, OUTPUT_FOLDER and event_data live in process memory while referenced.
Important precision: a variable stores a reference to an object; it is not a physical box containing the whole object. Memory addresses shown by examples such as id(obj) are implementation details and should not be hard-coded.
from datetime import datetime
from pathlib import Path
timestamp = datetime.now()
OUTPUT_FOLDER = Path(r"D:\SQF_Reports")
print(type(timestamp)) # <class 'datetime.datetime'>
print(type(OUTPUT_FOLDER)) # platform-specific Path subclass
print(timestamp.__class__)
print(id(timestamp)) # identity for this process run
10. Key Terminology
__new__() creates an instance; __init__() initializes it.self.@classmethod receiving the class conventionally as cls.@staticmethod, receiving neither automatically.__truediv__ define operator behavior.11. Summary Comparison
| Level | What it is | Purpose | Contains / represents | Examples |
|---|---|---|---|---|
| Module | File or package namespace | Organize and reuse code | Classes, functions, variables, submodules | datetime, pathlib, pandas |
| Class | Runtime blueprint/type | Define structure and behavior | Attributes, methods, descriptors | datetime, Path, DataFrame |
| Object | Specific runtime instance/value | Hold actual state and perform work | Concrete attribute values and class-provided behavior | timestamp, OUTPUT_FOLDER, event_data |
The module is the toolbox, the class is the tool design, and the object is the actual tool in your hand. Python variables are labels that refer to those runtime objects.
Hands-On Lab: Inspect Modules, Classes and Objects
Hands-on- Python 3.10 or later.
- Install pandas only for the final optional step.
- Create a temporary practice folder; do not point the exercise at production reports.
- Estimated time: 15 minutes.
Inspect a module and class
import pathlib
print(type(pathlib))
print(pathlib.Path)
print(type(pathlib.Path))pathlib reports as a module and Path behaves as a class/type.Create and inspect objects
from pathlib import Path
a = Path("reports")
b = Path("archive")
print(type(a), a.name)
print(type(b), b.name)
print(a is b)Compare attributes and methods
from datetime import datetime
stamp = datetime.now()
print(stamp.year)
print(stamp.strftime("%Y-%m-%d %H:%M:%S"))
print(callable(stamp.strftime))year supplies data, while strftime is callable behavior.Optional DataFrame check
import pandas as pd
data = pd.DataFrame({"Tag": ["Level", "Pressure"], "Value": [72.5, 4.8]})
print(type(data))
print(data.shape)
print(data.to_string(index=False))data is a DataFrame object with two rows, two columns and DataFrame behavior.Related Python and SQL Server Tutorials
Continue through the Softwell Python–SQL Server learning path:
- Python modules, classes and objects
- Python–SQL Server data type mapping
- Create a SQL Server database and table with Python
- Insert data into SQL Server with Python
- Read SQL Server data into pandas
- Complete Python SQL Server CRUD tutorial
- Export SQL Server data to Excel
- Create a Python EXE for WinCC Excel reports
Frequently asked questions
Is a Python module the same as a class?
No. A module is a file or package namespace that may contain classes, functions and variables. A class is one kind of object that can be defined inside it.
What is the difference between a class and an object?
A class defines structure and behavior. An object is a specific instance with actual state in memory.
What happens when Python imports a module?
Python locates and initializes the module, executes its top-level code once for that import cache entry, creates a module object, records it in sys.modules, and binds the imported name.
