Module = reusable Python code you import. Class = blueprint. Object = actual instance created from a class. Method = action an object can perform. Attribute = information or property belonging to an object.
Python Module, Class, Object, Method and Attribute Explained
This lesson is designed for learners who are seeing imported Python libraries for the first time. Instead of memorizing syntax, you will understand what each word means and how the parts connect.
Related Search Topics
Python module for beginners · Python class and object difference · Python method vs attribute · pathlib Path example
1. Python Code Architecture: Module → Class → Object → Method / Attribute
Before reading individual Python statements, first understand the architecture. A Python program is easier to read when you identify which layer each name belongs to.
Module → Class → Object → Method / Attribute
Read Python code by identifying where a name comes from, what creates the working object, what action it performs and what property it exposes.
Module
Reusable Python code or namespace.
Class / Function
A class creates objects; a function performs reusable work.
Object
A variable can reference a created working object.
Method
An action belonging to an object.
Attribute
Information/property belonging to an object.
Project Reading
Apply the same architecture to database/reporting code.
Code-rendered diagram: the diagram is searchable HTML text and requires no architecture image file.
For the first learner example, the architecture is:
pathlib → Path → folder → mkdir() └──→ name
| Architecture layer | pathlib example | Question to ask while reading code |
|---|---|---|
| Module | pathlib | Which reusable library has been imported? |
| Class | Path | Which blueprint/type creates the working object? |
| Object | folder | Which variable now refers to the created object? |
| Method | folder.mkdir() | What action is the object performing? |
| Attribute | folder.name | What information/property are we reading? |
Architecture of a Larger Python Program
When the program becomes larger, such as your SQL Server setup program, the same idea sits inside a broader program structure:
import pyodbc loads reusable SQL Server connectivity code.SERVER, DATABASE and DRIVER hold application settings.connect(), create_database(), create_event_table(), verify_objects() and main() organize the work into reusable steps.connection, cursor and error are runtime objects used while the program executes.cursor.execute(), connection.commit() and cursor.fetchone() perform work; attributes such as connection.autocommit or cursor.rowcount expose object information.connect(), create_database() and main() in your script are functions. pyodbc.connect() is also a module-level function. A method belongs to an object, for example connection.cursor() or cursor.execute().2. The Five Python Terms You Must Understand First
Start with this one table. It gives you a practical mental model for reading Python code.
| Python item | Example | Meaning |
|---|---|---|
| Module | pathlib | Contains reusable file and folder related Python tools. |
| Class | Path | A blueprint for creating objects that work with file and folder paths. |
| Object | folder | An actual object created by calling the Path class. |
| Method | mkdir() | An action performed by the object. |
| Attribute | folder.name | Information or a property belonging to the object. |
3. Your First Code: pathlib → Path → folder → mkdir() → name
from pathlib import Path folder = Path(r"D:\SQF_Reports")
folder.mkdir(exist_ok=True) print(folder.name)
This small program is enough to understand the basic structure used later in larger automation and reporting projects.
pathlibReusable path toolsPathBlueprint for pathsfolderYour path objectmkdir()Create a directoryfolder.nameRead folder name4. What Is a Module in Python?
A module is reusable Python code that can contain functions, classes, variables and other definitions. We import a module or something from a module so we can use code that has already been written.
from pathlib import PathHere, pathlib is the module. It provides tools for working with file-system paths. We are importing one specific tool from it: the Path class.
A simple way to remember it is:
Module = collection of reusable Python tools.
Instead of writing file/folder logic from zero, we import tested functionality and use it.
Two common import styles
import pathlib folder = pathlib.Path(r"D:\SQF_Reports")Or import only the class you need:
from pathlib import Path folder = Path(r"D:\SQF_Reports")Both are valid. For a first learner program, from pathlib import Path keeps the later code shorter and easier to read.
5. What Is a Class in Python?
A class is a blueprint used to create objects. In this lesson, Path is the class.
PathThe class defines how a path object behaves and what operations are available to it. You normally do not need to know the internal code of the class to use it.
Path classD:\SQF_ReportsPath(...)folder6. What Is an Object in Python?
An object is the actual value created from a class. Here:
folder = Path(r"D:\SQF_Reports")Path is the class and folder is the variable that refers to the resulting Path object.
Think of the relationship as:
Class Object
Path → folderOne class can be used to create many objects:
report_folder = Path(r"D:\SQF_Reports")
backup_folder = Path(r"D:\SQF_Backup")Both objects are created from the same Path class, but they represent different paths.
7. What Is a Method in Python?
A method is an action associated with an object. Methods are normally called using parentheses.
folder.mkdir(exist_ok=True)Read this from left to right:
folder→ the object.→ access something belonging to that objectmkdir→ the method name()→ call or execute the methodexist_ok=True→ allow the folder to already exist without raising an error
Easy recognition rule: when you see parentheses after an object member, such as folder.mkdir(), you are usually calling a method.
8. What Is an Attribute in Python?
An attribute is information or a property associated with an object. It is commonly accessed without parentheses.
folder.nameIf folder represents D:\SQF_Reports, then:
print(folder.name)prints:
SQF_ReportsCompare the two:
| Code | Type | Purpose |
|---|---|---|
folder.mkdir() | Method | Performs an action |
folder.name | Attribute | Provides information |
9. Read the Complete Code Like an Engineer
from pathlib import Path folder = Path(r"D:\SQF_Reports")
folder.mkdir(exist_ok=True) print(folder.name)- Import: Get the
Pathclass from thepathlibmodule. - Create object: Use
Path(...)to create a path object and store it infolder. - Call method: Use
folder.mkdir(...)to create the directory if required. - Read attribute: Use
folder.nameto get the final folder name. - Display: Use the built-in
print()function to show that value.
pathlib → ModulePath → Classfolder → Objectmkdir() → Methodfolder.name → Attribute10. How This Helps with datetime, pandas, pyodbc and openpyxl
After the five basic terms are clear, larger import statements become easier to understand.
| Import / library | Why you use it later | Example you may see |
|---|---|---|
datetime | Date and time handling | datetime.now() |
pathlib | File and folder paths | Path(...) |
pandas | Table/data processing and reports | pd.DataFrame(...) |
pyodbc | SQL Server connectivity | pyodbc.connect(...) |
openpyxl | Excel workbook formatting | worksheet.freeze_panes |
You do not need to master these libraries in Lesson 1. The goal is to recognize the structure when you meet them in later SQL Server and Excel-reporting labs.
11. Final Practical: Identify Module, Class, Object, Method and Attribute in Your SQL Server Code
Now apply the same architecture to a real program. This script creates SQF_DB, creates dbo.tblEvent when required, verifies the table and handles SQL Server errors.
| Python concept | Where it appears in this program | Meaning |
|---|---|---|
| Module | pyodbc | Imported SQL Server connectivity module. |
| Class | pyodbc.Error; runtime types such as Connection and Cursor | A class/type defines the kind of object. pyodbc.Error is the exception class caught by the program; pyodbc.connect() returns a Connection object and connection.cursor() returns a Cursor object. |
| Object | connection, cursor, error | Actual runtime objects used by the program. |
| Method | connection.cursor(), cursor.execute(), connection.commit(), cursor.fetchone() | Actions called on objects. |
| Attribute | connection.autocommit, cursor.rowcount (educational examples) | Values/properties read from objects without calling them. Your current script does not directly read one of these attributes. |
pyodbc.connect() is a function inside the module, not a method. The keyword argument autocommit=True is a function argument, not an attribute access. SERVER, DATABASE and DRIVER are variables/constants, not attributes.Your Code with Architecture Comments
"""Create SQF_DB and dbo.tblEvent when they do not already exist.""" import pyodbc # MODULE: pyodbc SERVER = r"SOFTWELL\WINCC" # Variable / configuration constant
DATABASE = "SQF_DB" # Variable / configuration constant
DRIVER = "ODBC Driver 17 for SQL Server" # Variable / configuration constant def connect(database_name, *, autocommit=False): # FUNCTION: user-defined function return pyodbc.connect( # FUNCTION: connect() belongs to pyodbc module f"DRIVER={{{DRIVER}}};" f"SERVER={SERVER};" f"DATABASE={database_name};" "Trusted_Connection=yes;" "TrustServerCertificate=yes;", autocommit=autocommit, # Function argument, NOT an attribute timeout=15, # Function argument ) # RETURNS: a Connection OBJECT def create_database(): # FUNCTION # DATABASE is a trusted constant. SQL identifiers cannot use ? parameters. with connect("master", autocommit=True) as connection: # connection = OBJECT (Connection object returned by pyodbc.connect) cursor = connection.cursor() # connection.cursor() = METHOD of the connection OBJECT # cursor = OBJECT (Cursor object returned by the cursor() method) cursor.execute(f""" IF DB_ID(N'{DATABASE}') IS NULL BEGIN CREATE DATABASE [{DATABASE}]; END; """) # cursor.execute() = METHOD of the cursor OBJECT def create_event_table(): # FUNCTION with connect(DATABASE) as connection: # connection = OBJECT cursor = connection.cursor() # cursor() = METHOD # cursor = OBJECT cursor.execute(""" IF OBJECT_ID(N'dbo.tblEvent', N'U') IS NULL BEGIN CREATE TABLE dbo.tblEvent ( DT datetime NOT NULL, TM varchar(10) NULL, SQF_No int NULL, ChargeNo varchar(50) NULL, Event_From varchar(100) NULL, Event_To varchar(100) NULL, Temp_Set float NULL, Temp_Act float NULL, Cp_Set float NULL, Cp_Act float NULL, Oil_Set float NULL, Oil_Act float NULL, Jacket_Set float NULL, Jacket_Act float NULL, Fan_Status varchar(10) NULL ); END; """) # execute() = METHOD of cursor OBJECT connection.commit() # commit() = METHOD of connection OBJECT def verify_objects(): # FUNCTION with connect(DATABASE) as connection: # connection = OBJECT cursor = connection.cursor() # cursor = OBJECT; cursor() = METHOD cursor.execute(""" SELECT DB_NAME() AS DatabaseName, OBJECT_ID(N'dbo.tblEvent', N'U') AS TableObjectId; """) # execute() = METHOD database_name, table_object_id = cursor.fetchone() # fetchone() = METHOD of cursor OBJECT # database_name and table_object_id = values returned from the query row if table_object_id is None: raise RuntimeError("dbo.tblEvent was not created.") # RuntimeError = built-in exception CLASS return database_name, table_object_id def main(): # FUNCTION: program controller try: create_database() # FUNCTION call print(f"Database [{DATABASE}] is available.") create_event_table() # FUNCTION call print("Table [dbo].[tblEvent] is available.") database_name, table_object_id = verify_objects() # FUNCTION call print(f"Verified database: {database_name}") print(f"Verified table object ID: {table_object_id}") except pyodbc.Error as error: # pyodbc = MODULE # Error = exception CLASS provided by pyodbc # error = exception OBJECT created when a pyodbc error occurs raise SystemExit(f"SQL Server setup failed: {error}") from error # SystemExit = built-in exception CLASS if __name__ == "__main__": # __name__ = special module-level variable used to detect direct execution main() # ============================================================
# FINAL OOP IDENTIFICATION FOR LEARNERS
# ============================================================
# MODULE : pyodbc
#
# CLASS : pyodbc.Error
# Connection and Cursor are the runtime object types used by pyodbc.
#
# OBJECT : connection
# cursor
# error
#
# METHOD : connection.cursor()
# cursor.execute(...)
# connection.commit()
# cursor.fetchone()
#
# ATTRIBUTE : The current program does not directly read a pyodbc object attribute.
# Examples for learning only:
# connection.autocommit # property/attribute of a Connection object
# cursor.rowcount # attribute of a Cursor object
#
# FUNCTION : pyodbc.connect(...)
# connect()
# create_database()
# create_event_table()
# verify_objects()
# main()
#
# IMPORTANT : Function and Method are not the same.
# pyodbc.connect() -> module-level FUNCTION
# connection.cursor() -> object METHOD
# cursor.execute() -> object METHOD
pyodbc → Modulepyodbc.connect() → Module-level functionconnection → Connection objectconnection.cursor() → Method → returns cursor objectcursor.execute() → Methodconnection.commit() → Methodcursor.fetchone() → Methodpyodbc.Error → Exception classerror → Exception objectconnection.autocommit / cursor.rowcount → Attribute examplesIdentify Module, Class, Object, Method and Attribute
- Python 3.x installed.
- Create a simple
.pyfile. - Use a test folder path suitable for your computer.
- Estimated time: 10 minutes.
Import Path
Type from pathlib import Path. Identify pathlib as the module and Path as the class.
Create the object
Type folder = Path(r"D:\SQF_Reports").
folder as an object reference created from Path.Call a method
Run folder.mkdir(exist_ok=True).
mkdir() as a method.Read an attribute
Run print(folder.name).
SQF_Reports and you can identify name as an attribute.Continue the Python + SQL Server Learning Path
Once you can read modules, classes, objects, methods and attributes, continue through the practical reporting series:
- Lab 1: Python modules, classes and objects
- Lab 2: Python Data Types for SQL Server Integration
- Lab 3: Create a SQL Server Database with Python and pyodbc
- Lab 4: Insert Values into SQL Server Using Python
- Lab 5: Read SQL Server Data with pyodbc and pandas
- Lab 6: Python + SQL Server CRUD
- Lab 7: Generate Excel Reports from SQL Server
- Lab 8: Convert Python to EXE for WinCC Excel Reports
Frequently Asked Questions
What is a module in Python?
A module is reusable Python code that you can import. It may contain functions, classes, variables and other definitions. In this lesson, pathlib is the module.
What is the difference between a class and an object?
A class is a blueprint. An object is a specific instance created from that class. Here, Path is the class and folder refers to an object created from it.
What is the difference between a method and an attribute?
A method performs an action and is usually called with parentheses, such as folder.mkdir(). An attribute provides information or a property, such as folder.name.
Is pathlib an external Python package?
No. pathlib is part of Python's standard library, so a normal Python installation already includes it.
Why learn these concepts before pandas and pyodbc?
Because pandas, pyodbc and openpyxl use the same basic object-oriented patterns. Once you can identify modules, classes, objects, methods and attributes, later database and Excel code becomes much easier to read.
Is pyodbc.connect() a function or a method?
pyodbc.connect() is a module-level function. It returns a Connection object. After that, calls such as connection.cursor(), connection.commit() and cursor.execute() are methods because they are called on objects.
