Object-Oriented Programming (OOP) is a software design paradigm that structures code into real-world entities modeled as objects. An object bundles both state (data held in attributes) and behavior (functions known as methods) together into a single cohesive unit. Python is fully object-oriented from the ground up.
Figure 31.1: The Student class blueprint instantiating two independent objects with unique memory IDs.
__init__ ConstructorClasses are declared using the class keyword. The __init__() dunder method is the class constructor:
class Student:
# Class Attribute (shared across all student instances):
university_name = "Delhi University"
def __init__(self, name: str, roll_no: int, marks: float):
# Instance Attributes (unique to each student object):
self.name = name
self.roll_no = roll_no
self.marks = marks
# Instance Method:
def display_details(self):
print(f"Roll #{self.roll_no} | Name: {self.name} | Marks: {self.marks}/100")
def has_passed(self) -> bool:
return self.marks >= 40.0
To create an object, call the class name like a function (which triggers __init__):
# Creating two distinct student objects:
s1 = Student("Aman Kumar", 101, 88.5)
s2 = Student("Priya Sharma", 102, 34.0)
s1.display_details()
print("Aman Passed?:", s1.has_passed()) # True
s2.display_details()
print("Priya Passed?:", s2.has_passed()) # False
print("University (Class Attribute):", Student.university_name)
| Feature | Class Attribute | Instance Attribute |
|---|---|---|
| Scope | Shared by all instances of the class. | Unique to each individual object. |
| Declaration | Defined directly in class body outside methods. | Defined inside __init__ using self.attr. |
| Memory | Allocated once when the class is loaded. | Allocated every time a new object is created. |
@classmethod) & Static Methods (@staticmethod)class Employee:
standard_raise = 1.05
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def set_raise_percentage(cls, new_raise):
cls.standard_raise = new_raise
@staticmethod
def is_workday(day_name):
return day_name.lower() not in ["saturday", "sunday"]
# Calling class & static methods:
Employee.set_raise_percentage(1.08)
print("Is Monday a workday?:", Employee.is_workday("Monday")) # True
s1.display_details(), Python automatically transforms this behind the scenes into Student.display_details(s1). The self parameter is required so the function body knows which object instance is invoking it.