Encapsulation, Inheritance, Polymorphism and Abstraction.
These principles form the baseline for writing clean, reusable and maintainable code.
Encapsulation (Data Protection)
Encapsulation is the practice of keeping data (attributes) and methods (functions) into a single unit (a class) while restricting direct access to some components. This prevents accidental data modification.
In Python, access restrictions are established by using underscores:
_variable: Protected (a warning to other developers not to access it outside the class).__variable: Private (triggers "name mangling" so it cannot be accessed directly from outside)
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance # Private attribute
# Getter method to safely access private data
def get_balance(self):
return self.__balance
# Setter method to safely modify private data
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
print("Invalid deposit amount!")
account = BankAccount("Alice", 1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
# print(account.__balance) # Throws AttributeErrorInheritance (Code Reusability):
Inheritance allows a child class to derive attributes and methods from a parent class. This prevents code duplication and keeps code DRY (Don't Repeat Yourself).
You can use the
super()function to call methods from the parent class inside the child class.
class Animal: # Parent Class
def eat(self):
print("This animal is eating.")
class Dog(Animal): # Child Class inheriting from Animal
def bark(self):
print("Woof woof!")
my_dog = Dog()
my_dog.eat() # Output: This animal is eating. (Inherited method)
my_dog.bark() # Output: Woof woof! (Child method)Polymorphism (Flexibility):
Polymorphism literally means "many forms". It allows different classes to have methods with the same name but different implementations.
This allows you to write flexible functions that can handle multiple types of objects identically.
class Cat:
def speak(self):
return "Meow"
class Dog:
def speak(self):
return "Woof"
# A function that accepts any object with a 'speak' method
def make_animal_sound(animal_object):
print(animal_object.speak())
cat = Cat()
dog = Dog()
make_animal_sound(cat) # Output: Meow
make_animal_sound(dog) # Output: WoofAbstraction (Hiding Complexity):
Abstraction hides internal complexities and exposes only essential features to the user. For example, when you turn on a car, you only push a button; you don't need to know how the engine works internally.
Python achieves abstraction using the built-in
abc(Abstract Base Classes) module and the@abstractmethoddecorator.An abstract class cannot be instantiated directly; it acts as a blueprint that forces child classes to implement specific methods.
from abc import ABC, abstractmethod
class Vehicle(ABC): # Abstract Base Class
@abstractmethod
def start_engine(self):
pass
class Car(Vehicle):
def start_engine(self):
print("Car engine started. Vroom!")
# my_vehicle = Vehicle() # Throws TypeError (Cannot instantiate abstract class)
my_car = Car()
my_car.start_engine() # Output: Car engine started. Vroom!