Python Basics · Beginner Lesson ·

Python Modules, Classes & Objects Explained

Your first step in reading real Python code. Learn the meaning of module, class, object, method and attribute using one simple pathlib example before moving to pandas, pyodbc and openpyxl.

Beginner-first Python Module → Class → Object Method vs Attribute Foundation for reporting projects

Lab Overview

Python Learning SeriesEstimated time: 20 minutesDifficulty: Beginner

What You’ll Learn

  • Python code architecture: Module → Class → Object → Method / Attribute
  • What a Python module means
  • Class vs object
  • Method vs attribute
  • How to read Path code step by step
  • How the same architecture appears in a real pyodbc SQL Server program
Quick answer

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.

Foundation • Python Code Architecture

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.

1

Module

Reusable Python code or namespace.

from pathlib import Path
2

Class / Function

A class creates objects; a function performs reusable work.

Path(...) | pyodbc.connect(...)
3

Object

A variable can reference a created working object.

folder = Path(r"D:\Reports")
4

Method

An action belonging to an object.

folder.mkdir(exist_ok=True)
5

Attribute

Information/property belonging to an object.

folder.name
6

Project Reading

Apply the same architecture to database/reporting code.

connection.cursor() cursor.execute(sql)
pathlibStandard-library module
PathClass
folderObject
mkdir() / nameMethod / attribute
Architecture:ModuleClass / FunctionObjectMethod / AttributeProject 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 layerpathlib exampleQuestion to ask while reading code
ModulepathlibWhich reusable library has been imported?
ClassPathWhich blueprint/type creates the working object?
ObjectfolderWhich variable now refers to the created object?
Methodfolder.mkdir()What action is the object performing?
Attributefolder.nameWhat 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:

1. Import layerimport pyodbc loads reusable SQL Server connectivity code.
2. Configuration layerSERVER, DATABASE and DRIVER hold application settings.
3. Function layerconnect(), create_database(), create_event_table(), verify_objects() and main() organize the work into reusable steps.
4. Object layerconnection, cursor and error are runtime objects used while the program executes.
5. Action / data layerMethods such as cursor.execute(), connection.commit() and cursor.fetchone() perform work; attributes such as connection.autocommit or cursor.rowcount expose object information.
Important beginner distinction: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 itemExampleMeaning
ModulepathlibContains reusable file and folder related Python tools.
ClassPathA blueprint for creating objects that work with file and folder paths.
ObjectfolderAn actual object created by calling the Path class.
Methodmkdir()An action performed by the object.
Attributefolder.nameInformation or a property belonging to the object.
First learner rule: Do not try to learn every Python library at once. First learn to identify these five parts. Once you can identify them, larger programs become much easier to read.

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.

ModulepathlibReusable path tools
ClassPathBlueprint for paths
ObjectfolderYour path object
Methodmkdir()Create a directory
Attributefolder.nameRead folder name

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

Here, 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.

Path

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

BlueprintPath class
InputD:\SQF_Reports
CreateCall Path(...)
Objectfolder
UseMethods + attributes

6. 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 → folder

One 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 object
  • mkdir → the method name
  • () → call or execute the method
  • exist_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.name

If folder represents D:\SQF_Reports, then:

print(folder.name)

prints:

SQF_Reports

Compare the two:

CodeTypePurpose
folder.mkdir()MethodPerforms an action
folder.nameAttributeProvides 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)
  1. Import: Get the Path class from the pathlib module.
  2. Create object: Use Path(...) to create a path object and store it in folder.
  3. Call method: Use folder.mkdir(...) to create the directory if required.
  4. Read attribute: Use folder.name to get the final folder name.
  5. Display: Use the built-in print() function to show that value.
The main concept:
pathlib → Module
Path → Class
folder → Object
mkdir() → Method
folder.name → Attribute

10. How This Helps with datetime, pandas, pyodbc and openpyxl

After the five basic terms are clear, larger import statements become easier to understand.

Import / libraryWhy you use it laterExample you may see
datetimeDate and time handlingdatetime.now()
pathlibFile and folder pathsPath(...)
pandasTable/data processing and reportspd.DataFrame(...)
pyodbcSQL Server connectivitypyodbc.connect(...)
openpyxlExcel workbook formattingworksheet.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 conceptWhere it appears in this programMeaning
ModulepyodbcImported SQL Server connectivity module.
Classpyodbc.Error; runtime types such as Connection and CursorA 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.
Objectconnection, cursor, errorActual runtime objects used by the program.
Methodconnection.cursor(), cursor.execute(), connection.commit(), cursor.fetchone()Actions called on objects.
Attributeconnection.autocommit, cursor.rowcount (educational examples)Values/properties read from objects without calling them. Your current script does not directly read one of these attributes.
Do not misclassify: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

MODULE = imported reusable codeCLASS = blueprint/typeOBJECT = runtime instanceMETHOD = object actionATTRIBUTE = object data/property
"""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
Architecture to remember:
pyodbc → Module
pyodbc.connect() → Module-level function
connection → Connection object
connection.cursor() → Method → returns cursor object
cursor.execute() → Method
connection.commit() → Method
cursor.fetchone() → Method
pyodbc.Error → Exception class
error → Exception object
connection.autocommit / cursor.rowcount → Attribute examples
Hands-on beginner lab

Identify Module, Class, Object, Method and Attribute

Beginner
Before you start
  • Python 3.x installed.
  • Create a simple .py file.
  • Use a test folder path suitable for your computer.
  • Estimated time: 10 minutes.
1

Import Path

Type from pathlib import Path. Identify pathlib as the module and Path as the class.

You can name the module and class correctly.
2

Create the object

Type folder = Path(r"D:\SQF_Reports").

You can identify folder as an object reference created from Path.
3

Call a method

Run folder.mkdir(exist_ok=True).

The directory exists and you can identify mkdir() as a method.
4

Read an attribute

Run print(folder.name).

Python prints 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:

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.

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

Get the Python Scripting syllabus

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

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

Start Python with the right foundation

Understand the code structure first, then progress to SQL Server, pandas, Excel reporting and industrial automation projects.

Request Course Details
Complete Python for Industrial Automation Learning Path

Use Previous / Next for sequential training, or open any topic directly.

Verified learning pathway

Discuss Python Scripting Training

Explore beginner-to-industrial Python curriculum, practical labs and batch options.

Content reviewed: 13 September 2026

☎ Call WhatsApp ✉ Email Enquire Now