Python 3 — OOP: Classes & Objects
Object-Oriented Programming (OOP) is a design pattern that models software after real-world objects. Instead of writing disconnected variables and functions, OOP binds them together inside a single, unified capsule called a Class.
Think of a **Class** as a blueprint (like the architectural blueprint for a house). You can't live inside a blueprint. An **Object** is the actual house constructed from that blueprint. You can build as many houses as you want from a single blueprint!
We define classes using the class keyword. The __init__ function is the constructor method that initializes an object when it's created. The self parameter represents the current object instance:
class Student:
# Constructor (Blueprint Setup)
def __init__(self, name, score):
self.name = name # Attribute
self.score = score # Attribute
# Class Method (Action)
def display_info(self):
print(f"Student: {self.name}, Score: {self.score}/100")
# Constructing object instances
student1 = Student("Alice", 92)
student2 = Student("Balaji", 98)
# Running methods on instances
student1.display_info()
student2.display_info()
You can access and modify attributes directly on object instances using the dot (.) syntax:
student1.score = 95 # Modify Alice's score
student1.display_info() # Student: Alice, Score: 95/100
The self parameter is mandatory inside class methods. When you call student1.display_info(), Python passes the student1 object as the first parameter (self) under the hood. This is how the method knows which object's attributes to display.
Create a class called 'Car' with constructor attributes for 'brand', 'model', and 'year'. Add a method called 'drive()' that prints: "[brand] [model] is driving away!". Instantiate a car object and call the method.