Why OOP Matters
Object-Oriented Programming (OOP) is not just a buzzword. It’s the foundation of scalable, maintainable, and reusable code. Python, being an object-oriented language, allows developers to model real-world entities using classes and objects. If you’re building anything beyond a simple script, OOP is essential.
In this post, we’ll cover:
- Classes and Objects
- Constructors (
__init__) - Methods vs. Functions
- Inheritance and code reusability
Classes and Objects: The Blueprint and the Product
A class is a blueprint. An object is an instance of that blueprint.
python
class Car:
pass
my_car = Car() # Object created
But an empty class is useless. Let’s add data and behavior.
Constructors: The __init__ Method
The constructor initializes an object’s attributes when it is created.
python
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
emp1 = Employee("Alice", 50000)
print(emp1.name) # Alice
self refers to the current instance. Without self, Python cannot distinguish between instance attributes and local variables.
Methods vs. Functions: The Critical Difference
- Function: Independent block of code. Defined with
defoutside a class. - Method: A function that belongs to a class. It takes
selfas the first parameter.
python
# Function
def greet():
return "Hello"
# Method
class Person:
def greet(self):
return "Hello"
Methods operate on object data. Functions operate on inputs. Never confuse them in interviews or documentation.
Inheritance: Write Less, Reuse More
Inheritance allows a child class to acquire properties and methods from a parent class. This is where OOP saves thousands of lines of code.
python
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Bark"
dog = Dog()
print(dog.speak()) # Bark
The Dog class inherited speak from Animal but overrode it. You can also use super() to call the parent method.
python
class Cat(Animal):
def speak(self):
return super().speak() + " but meow"
print(Cat().speak()) # Some sound but meow
Types of Inheritance:
- Single: One parent, one child.
- Multiple: One child, multiple parents.
- Multilevel: Grandparent → Parent → Child.
Real-World Benefit: Code Reusability
Imagine you have 10 types of users (Admin, Guest, Editor, etc.). Without inheritance, you’d duplicate login logic 10 times. With inheritance:
python
class User:
def login(self):
return "Logged in"
class Admin(User):
def delete_user(self):
return "User deleted"
Admin gets login() for free. That’s reusability.
Leave a Reply