Classes and Objects
Definition: A class is a blueprint, template, or prototype used to define the structure and behavior of something. An object is a real-world instance or copy created from that class blueprint.
Why: Classes and objects introduce Object-Oriented Programming (OOP) in Python. OOP is a powerful way to structure your code by grouping related data (attributes) and actions (methods) into independent, reusable entities, making large codebases much easier to scale and manage.
The Blueprint Analogy
Think of a class as an architectural blueprint for a house. The blueprint itself isn't a house—it just describes how a house should look and be built. An object is the actual, physical house built using that blueprint. You can build as many individual houses (objects) from that single blueprint as you want.
Example
class Student:
# The Constructor Method
def __init__(self, name, age):
self.name = name # Instance variable (Attribute)
self.age = age # Instance variable (Attribute)
# A Custom Method
def show(self):
print(self.name, self.age)
# Creating an Object (Instantiation)
s1 = Student("Ravi", 20)
# Calling a Method on the Object
s1.show() # Output: Ravi 20
Explanation of Core Components
- The
classKeyword: This is used to declare a new user-defined data type (in this case,Student). By convention, class names use PascalCase (capitalizing the first letter of each word). - The
__init__()Method: Known as the **constructor**, this special method runs automatically every single time you create a new object from the class. It initializes the object's starting attributes. - The
selfParameter: This represents the specific object you are currently creating or working with. It links the data attributes (likenameandage) directly to that particular instance. - Instantiating an Object: Writing
s1 = Student("Ravi", 20)triggers the constructor, creates a brand-new student object nameds1, and assigns it the values "Ravi" and 20.
Key Notes
- You can create multiple distinct objects from a single class (e.g.,
s2 = Student("Anu", 19)). Each object holds its own independent data. - Functions defined inside a class are called methods, while variables inside a class are called attributes.
- Python objects are dynamic, meaning you can access and modify their attributes directly using dot notation (e.g.,
s1.age = 21).
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute
🏋️ Test Yourself With Exercises
Take our quiz on Classes and Objects to test your knowledge.
Exercise »