Python · Industry 4.0 Technical Blog

Python Modules, Classes and Objects Explained with Examples

Learn the three levels of Python code organization—from reusable module files, to class blueprints, to live objects holding real data—with practical examples drawn from industrial SQL-to-Excel reporting.

2,500+ engineers trained Industrial project examples 21+ years, Chinchwad, Pune

Lab Overview

Lab 1 of 8Estimated time: 30 minutesDifficulty: Beginner

Prerequisites / What You’ll Need

  • Python 3.x
  • A code editor or Python IDE
  • Basic variables and functions knowledge
Quick answer

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.attribute and object.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

ModulePython file or package
datetime, pathlib, pandas
ClassBlueprint exposed by a module
datetime, Path, DataFrame
ObjectLive instance with actual data
timestamp, OUTPUT_FOLDER, event_data
MODULE / 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/packageTypical contents used in reporting
datetimedatetime, date, time, timedelta
pathlibPath, PurePath, PureWindowsPath
sysexit(), argv, platform
pandasDataFrame, Series, read_sql_query()
pyodbcconnect(), Connection and Cursor objects
openpyxlWorkbook, 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

  1. Write or import a module. Python locates the file/package and creates a module namespace.
  2. Define or obtain a class. The class statement executes during import, or the class is imported directly.
  3. Create an object. Calling a class normally invokes object construction and initialization.
  4. 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.

Book a Free Demo Class

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/sourceClass or callableObject variableExample use
datetimedatetime.now()timestamptimestamp.strftime(...)
pathlibPathOUTPUT_FOLDEROUTPUT_FOLDER.mkdir()
pandasread_sql_query() → DataFrameevent_dataevent_data.to_excel()
pyodbcconnect() → Connectionconnectionconnection.cursor()
openpyxl.stylesFontheader_fontcell.font = header_font
openpyxl.stylesAlignmentalignmentcell.alignment = alignment
openpyxl.stylesPatternFillheader_fillcell.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

ModuleA Python file or package namespace containing reusable code.
ClassA blueprint that defines attributes and methods.
Object / instanceA specific runtime value created from a class.
InstantiationCreating an object, commonly by calling a class.
MethodA function defined on a class and accessed through the class or object.
Attribute / propertyNamed data or managed access available through dot notation.
Constructor and initializer__new__() creates an instance; __init__() initializes it.
Instance methodA method receiving the instance conventionally as self.
Class methodA @classmethod receiving the class conventionally as cls.
Static methodA namespaced function declared with @staticmethod, receiving neither automatically.
Operator overloadingSpecial methods such as __truediv__ define operator behavior.
Parameter / return valueInput accepted by a callable / output sent back to the caller.
InheritanceA child class derives behavior and structure from a parent class.
NamespaceA mapping between names and objects, such as a module’s global namespace.

11. Summary Comparison

LevelWhat it isPurposeContains / representsExamples
ModuleFile or package namespaceOrganize and reuse codeClasses, functions, variables, submodulesdatetime, pathlib, pandas
ClassRuntime blueprint/typeDefine structure and behaviorAttributes, methods, descriptorsdatetime, Path, DataFrame
ObjectSpecific runtime instance/valueHold actual state and perform workConcrete attribute values and class-provided behaviortimestamp, OUTPUT_FOLDER, event_data
Remember it this way

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
Before you start
  • 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.
1

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.
2

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)
Both objects belong to the path class family, hold different path data, and have distinct identities.
3

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.
4

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:

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.

Reviewed by Bhawesh Kumar SinghIndustrial Automation Trainer and Industry 4.0 Consultant · Softwell Automation · 21+ years industry experience

Get the full Python training syllabus + free demo class

Share your details—a Softwell advisor will contact you with batch dates, fees and project-practice options.

No spam. Used only to share course details for this enquiry.

Learn Python with practical industrial examples

Join live online, Pune classroom or corporate in-plant Industry 4.0 training.

Request Course Details
Verified learning pathway

Discuss Python and Industry 4.0 Training

Explore practical curriculum, software, hardware and batch options for this technology.

Content reviewed: 2 August 2026

☎ Call WhatsApp ✉ Email Enquire Now