Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Difference Between Classes and Objects

Python Class vs Object - Complete Guide

Understand the key distinction between classes and objects — the foundation of OOP.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Class vs Object — The Core Distinction
  • Understanding Classes
  • Understanding Objects
  • Side-by-Side Comparison
  • Key Differences
  • Examples in Action
  • Common Misconceptions
  • Try It Yourself
  • Quick Quiz
  • Frequently Asked Questions
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • What is a class — the blueprint for creating objects
  • What is an object — an instance of a class
  • Key differences — how classes and objects differ
  • Real-world analogies — making the concept clear
  • Common misconceptions — what people often get wrong
  • Practical examples — seeing the difference in action

Class vs Object — The Core Distinction

One of the most common questions beginners ask is: "What's the difference between a class and an object?" It's a great question, and understanding the answer is essential for mastering Object-Oriented Programming.

The short answer: A class is a blueprint or template. An object is a specific instance built from that blueprint. Think of a class like a cookie cutter, and objects like the cookies you make with it. You can make many cookies from one cookie cutter.

This distinction might seem simple, but it's the foundation of OOP. Once you truly understand it, everything else in OOP becomes much clearer.

💡 Key concept: A class defines what objects will look like and how they'll behave. An object is the actual thing that exists in memory. One class can create many objects.

Understanding Classes

1

What is a Class?

A class is a blueprint for creating objects. It defines the structure (attributes) and behavior (methods) that all objects of that type will have. But the class itself is not an object — it's just a definition.

# A class is a blueprint
class Car:
    """A blueprint for creating car objects"""
    
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.mileage = 0
    
    def drive(self, miles):
        self.mileage += miles
        return f"Drove {miles} miles. Total mileage: {self.mileage}"
    
    def get_info(self):
        return f"{self.year} {self.make} {self.model}, {self.mileage} miles"

# The Car class is just a blueprint.
# No car objects exist yet.

# Let's examine what the class defines:
# 1. What data cars will have: make, model, year, mileage
# 2. What behavior cars will have: drive(), get_info()
# 3. What the initial state of a new car will be

# The class doesn't have values for these things.
# It just defines what they will be.
                                

Key characteristics of a class:

  • Abstract — it exists as code, not as a thing in memory
  • Defines structure — specifies what attributes objects will have
  • Defines behavior — specifies what methods objects will have
  • Reusable — one class can create many objects
  • No data — the class itself doesn't hold data (unless you use class attributes)
  • Created with the class keyword — defined in code

Class analogy:

  • Class = a recipe for chocolate chip cookies
  • Class = a blueprint for a house
  • Class = a mold for making plastic toys

Quick Check: What is a class? (Answer: A blueprint or template for creating objects)

Understanding Objects

2

What is an Object?

An object is a specific instance of a class. It's the actual thing that exists in memory with its own data. If a class is a blueprint, an object is the building built from that blueprint.

# Objects are specific instances of a class

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.mileage = 0
    
    def drive(self, miles):
        self.mileage += miles
        return f"Drove {miles} miles. Total mileage: {self.mileage}"
    
    def get_info(self):
        return f"{self.year} {self.make} {self.model}, {self.mileage} miles"

# Now we create objects (specific cars)
my_car = Car("Toyota", "Camry", 2022)
your_car = Car("Honda", "Civic", 2023)
mom_car = Car("Tesla", "Model 3", 2024)

# Each object has its own data
print(my_car.get_info())   # 2022 Toyota Camry, 0 miles
print(your_car.get_info()) # 2023 Honda Civic, 0 miles
print(mom_car.get_info())  # 2024 Tesla Model 3, 0 miles

# Each object can perform behaviors with its own data
print(my_car.drive(100))   # Drove 100 miles. Total mileage: 100
print(your_car.drive(50))  # Drove 50 miles. Total mileage: 50

# Objects are independent
print(my_car.get_info())   # 2022 Toyota Camry, 100 miles
print(your_car.get_info()) # 2023 Honda Civic, 50 miles
                                

Key characteristics of an object:

  • Concrete — it exists in memory
  • Has state — it has specific attribute values
  • Has behavior — it can perform methods
  • Unique identity — each object has its own identity
  • Independent — changes to one object don't affect others
  • Created from a class — objects are instantiated from classes

Object analogy:

  • Object = an actual batch of chocolate chip cookies
  • Object = a specific house built from the blueprint
  • Object = a plastic toy made from the mold

Quick Check: What is an object? (Answer: A specific instance of a class that exists in memory)

Side-by-Side Comparison

3

Seeing the Difference Clearly

Let's compare classes and objects directly to see how they differ in every aspect.

# Classes and Objects Side-by-Side

# 1. Definition
# Class: defined using the class keyword
class Person:
    """A blueprint for people"""
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Object: created by calling the class
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# 2. Purpose
# Class: defines what people will look like and do
# Object: a specific person with specific data

# 3. Memory
# Class: exists only as code
# Object: exists in memory with its own data

# 4. Data
# Class: no data (or shared class data)
class Employee:
    company = "Tech Corp"  # Class attribute
    def __init__(self, name):
        self.name = name    # Instance attribute

# Object: has its own data
emp1 = Employee("Alice")
emp2 = Employee("Bob")

print(emp1.company)  # Tech Corp (shared)
print(emp2.company)  # Tech Corp (shared)
print(emp1.name)     # Alice (unique)
print(emp2.name)     # Bob (unique)

# 5. Methods
# Class: defines methods but doesn't execute them
# Object: executes methods with its own data

# 6. Relationship
# Class: one class can create many objects
# Object: belongs to exactly one class
                                
Aspect Class Object
Definition Blueprint or template Instance of a class
Purpose Defines structure and behavior Holds specific data and performs actions
Exists in Code Memory
Data No data or shared data Has its own data
Methods Defines methods Executes methods with its own data
Created with class keyword Calling the class
Number One class definition Many objects can be created

Quick Check: What is the main difference between a class and an object? (Answer: A class is a blueprint; an object is an instance of that blueprint)

Key Differences

4

The Most Important Distinctions

While the table above covers many differences, there are a few key distinctions that are especially important to understand.

# Key Differences Between Classes and Objects

# 1. Existence
# A class is just a definition in your code.
# An object actually exists in memory.

class Dog:
    """This is just a definition - no dog exists yet"""
    def __init__(self, name):
        self.name = name

# Create an object - now a dog exists in memory
my_dog = Dog("Buddy")

# 2. Data Storage
# A class doesn't store data.
# Each object stores its own data.

class Book:
    # No data stored in the class
    def __init__(self, title, author):
        self.title = title
        self.author = author

book1 = Book("Python Guide", "John Smith")
book2 = Book("Data Science", "Jane Doe")

# Each object has its own data
print(book1.title)  # Python Guide
print(book2.title)  # Data Science

# 3. Behavior
# A class defines methods.
# Objects execute methods with their own data.

class Calculator:
    def add(self, a, b):
        return a + b

# The class defines add(), but doesn't execute it
calc = Calculator()
result = calc.add(5, 3)  # The object executes it

# 4. Creation
# A class is created once in code.
# Objects are created as needed.

# One class definition
class Car:
    pass

# Many objects from that class
car1 = Car()
car2 = Car()
car3 = Car()

# 5. Relationship
# A class is a type.
# An object is an instance of that type.

# Dog is a type
# my_dog is an instance of Dog
print(type(Dog))        # 
print(type(my_dog))     # 
                                

The most important thing to remember:

  • A class is a blueprint — it tells you what objects will look like
  • An object is the actual thing — it exists in memory with specific data
  • One class can create many objects — each with its own data

Quick Check: Can one class create multiple objects? (Answer: Yes, one class can create many objects)

Examples in Action

5

Seeing the Difference in Real Code

Let's look at more examples to really cement the difference between classes and objects. Each example will show you how the class defines the structure and how objects bring that structure to life.

# Example 1: A Restaurant System

class MenuItem:
    """Blueprint for menu items"""
    def __init__(self, name, price, category):
        self.name = name
        self.price = price
        self.category = category
        self.available = True
    
    def get_info(self):
        status = "Available" if self.available else "Sold Out"
        return f"{self.name} (${self.price}) - {self.category} - {status}"
    
    def toggle_availability(self):
        self.available = not self.available
        return f"{self.name} is now {'available' if self.available else 'unavailable'}"

# The MenuItem class is just a blueprint.
# Let's create some actual menu items (objects)
burger = MenuItem("Burger", 9.99, "Main")
pizza = MenuItem("Pizza", 12.99, "Main")
salad = MenuItem("Salad", 6.99, "Side")

# Each object has its own data
print(burger.get_info())   # Burger ($9.99) - Main - Available
print(pizza.get_info())    # Pizza ($12.99) - Main - Available

# Changing one object doesn't affect others
print(pizza.toggle_availability())  # Pizza is now unavailable
print(burger.get_info())   # Burger ($9.99) - Main - Available (unchanged)
print(pizza.get_info())    # Pizza ($12.99) - Main - Sold Out

# Example 2: A University System

class Student:
    """Blueprint for students"""
    def __init__(self, name, student_id, major):
        self.name = name
        self.student_id = student_id
        self.major = major
        self.gpa = 0.0
        self.courses = []
    
    def add_course(self, course):
        self.courses.append(course)
        return f"{self.name} added {course}"
    
    def set_gpa(self, gpa):
        self.gpa = gpa
        return f"{self.name}'s GPA is now {gpa}"
    
    def get_info(self):
        return f"{self.name} ({self.student_id}) - Major: {self.major}, GPA: {self.gpa}"

# The Student class is just a definition.
# Let's create some students (objects)
alice = Student("Alice", "S001", "Computer Science")
bob = Student("Bob", "S002", "Mathematics")
charlie = Student("Charlie", "S003", "Physics")

# Each student has their own data
print(alice.get_info())    # Alice (S001) - Major: Computer Science, GPA: 0.0
print(bob.get_info())      # Bob (S002) - Major: Mathematics, GPA: 0.0

# Each student can perform actions independently
print(alice.add_course("Python Programming"))  # Alice added Python Programming
print(bob.add_course("Calculus"))              # Bob added Calculus
print(alice.set_gpa(3.8))                      # Alice's GPA is now 3.8
print(bob.set_gpa(3.2))                        # Bob's GPA is now 3.2

# Alice and Bob are independent objects
print(alice.get_info())    # Alice (S001) - Major: Computer Science, GPA: 3.8
print(bob.get_info())      # Bob (S002) - Major: Mathematics, GPA: 3.2
                                

What these examples show:

  • One class — MenuItem and Student are single blueprints
  • Many objects — multiple items and students created from the same blueprint
  • Independent data — each object has its own attribute values
  • Independent behavior — changes to one object don't affect others

Quick Check: Can two objects of the same class have different attribute values? (Answer: Yes, each object has its own data)

Common Misconceptions

6

What People Often Get Wrong

Even experienced programmers sometimes confuse classes and objects. Here are some common misconceptions and why they're wrong.

# Common Misconceptions About Classes and Objects

# Misconception 1: "A class and an object are the same thing"
# WRONG: A class is a blueprint; an object is an instance.

# Misconception 2: "The class is the thing that holds data"
# WRONG: The class defines what data objects will have,
# but the objects themselves hold the data.

# Misconception 3: "You only need one object per class"
# WRONG: You can create as many objects as you need from one class.

# Misconception 4: "Changing the class changes all objects"
# WRONG: Changing a class doesn't affect existing objects.
# (Though adding new methods will be available to all objects)

# Let's demonstrate:

class Person:
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        return f"Hello, I'm {self.name}"

# Create objects
alice = Person("Alice")
bob = Person("Bob")

# Each object has its own data
print(alice.greet())  # Hello, I'm Alice
print(bob.greet())    # Hello, I'm Bob

# Misconception 5: "Objects are just data containers"
# WRONG: Objects combine data AND behavior (methods)

class Calculator:
    def add(self, a, b):
        return a + b
    
    def multiply(self, a, b):
        return a * b

calc = Calculator()
print(calc.add(5, 3))      # 8
print(calc.multiply(5, 3)) # 15

# Misconception 6: "You must create an object to use a class"
# Actually, you can use class methods without creating objects
# But for regular instances, you need objects.
                                

Remember these facts:

  • Class = blueprint, Object = actual thing
  • Class defines structure and behavior
  • Object has specific data and performs actions
  • One class can create many objects
  • Objects are independent — changes to one don't affect others

Quick Check: Can changing a class affect existing objects? (Answer: No, existing objects are independent)

Try It Yourself

Experiment with classes and objects in the editor below.

Loading Pyodide... 0%
Python Code Editor
========================================
CLASS VS OBJECT PRACTICE
========================================

1. DEFINING A CLASS

2. CREATING OBJECTS

3. EACH OBJECT HAS ITS OWN DATA
Dell XPS 13 ($1200) - OFF
Apple MacBook Pro ($2000) - OFF

4. OBJECTS ARE INDEPENDENT
Dell XPS 13 is now ON
Dell XPS 13 ($1200) - ON
Apple MacBook Pro ($2000) - OFF

5. ONE CLASS, MULTIPLE OBJECTS
Lenovo ThinkPad ($1000) - OFF
HP Spectre ($1100) - OFF
Asus ZenBook ($900) - OFF

Class vs Object practice complete!
🏆

You've Got It!

You now understand the key difference between classes and objects in Python. You know that a class is a blueprint and an object is an instance of that blueprint.

Quick Quiz

Test what you've learned:

1. What is a class?
2. What is an object?
3. Can one class create multiple objects?
4. Where does an object store its data?
5. If you change one object, does it affect other objects of the same class?

Frequently Asked Questions

What is the easiest way to remember the difference? ▼

Think of a class like a cookie cutter and objects like the cookies. The cookie cutter (class) defines the shape, but the cookies (objects) are the actual things you can eat. You can make many cookies from one cookie cutter.

Can I create an object without a class? ▼

No, objects are always created from a class. Even if you're using built-in types like lists or strings, you're creating objects from built-in classes. In Python, everything is an object, and every object has a class.

Is a class also an object? ▼

Yes! In Python, classes are themselves objects (instances of the 'type' class). This is part of Python's "everything is an object" philosophy. But for learning purposes, it's easier to think of classes and objects as separate concepts.

What's a common interview question about class vs object? ▼

Common questions include: "What is the difference between a class and an object?" "Explain the relationship between classes and objects" and "Can you create multiple objects from one class?"

How many objects can I create from one class? ▼

There's no limit! You can create as many objects as you need from a single class. Each object will be independent with its own data. This is one of the main advantages of OOP — reusing a blueprint to create many instances.

What happens to objects when I change the class? ▼

Existing objects are not affected by changes to the class definition (unless you're changing class attributes that are shared). New methods added to the class will be available to existing objects, but existing data remains unchanged.

Where to Go From Here

Now that you understand the difference between classes and objects, check out these related topics:

Constructors

Learn more about the __init__ method and constructors.

Learn More →

Destructor

Learn about destructors and object cleanup.

Learn More →

Inheritance

Learn how to create class hierarchies with inheritance.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: OOP vs Procedural Programming Next: Constructors →