Object-Oriented Programming

A Python-centric guide to the four pillars of OOP.

1. Classes & Objects

A Class is a blueprint; an Object is an instance of that blueprint.

class Dog:
    def __init__(self, name):
        self.name = name # Attribute

    def bark(self):
        return "Woof!"

my_dog = Dog("Buddy") # Object creation

2. The Four Pillars

Encapsulation

Restricting access to methods and variables to prevent direct data modification. In Python, we use a single _ (protected) or double __ (private) underscore.

Inheritance

Allowing a class (child) to derive attributes and methods from another class (parent).

class Puppy(Dog): # Inherits from Dog
    def wobble(self):
        return "Puppy is walking!"

Polymorphism

The ability of different classes to be treated as instances of the same general class through the same interface (e.g., different animals having the same speak() method).

Abstraction

Hiding complex implementation details and only showing the necessary features of an object. Usually handled via abc module in Python.