Index
Abstraction
Encapsulation
Inheritance
Polymorphism
1. Abstraction
Definition:
Abstraction is the process of hiding the implementation details of a function or method and only exposing the essential features. In Python, abstraction is typically achieved through abstract classes and interfaces (using the abc
module).
Use-Case Example:
Abstraction is used when you want to define a common interface for a group of related classes, ensuring that each class implements the required functionality without exposing the complex internal logic.
Syntax:
from abc import ABC, abstractmethod
class AbstractClass(ABC):
@abstractmethod
def abstract_method(self):
pass
Rules:
An abstract class cannot be instantiated directly.
All subclasses must implement the abstract methods of the abstract class.
Basic Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
# Creating objects of subclasses
dog = Dog()
cat = Cat()
print(dog.sound()) # Output: Bark
print(cat.sound()) # Output: Meow
2. Encapsulation
Definition:
Encapsulation is the concept of bundling the data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some of an object's components to protect the internal state.
Use-Case Example:
Encapsulation ensures that the internal state of an object is protected from unintended modification by external code.
Syntax:
class ClassName:
def __init__(self):
self.public_attribute = "Public"
self._protected_attribute = "Protected"
self.__private_attribute = "Private"
Rules:
Public attributes and methods are accessible from outside the class.
Protected attributes (denoted by a single underscore
_
) are intended to be accessed within the class or subclass.Private attributes (denoted by double underscores
__
) are only accessible within the class.
Basic Example:
class Car:
def __init__(self):
self.__engine = "Private Engine"
def get_engine(self):
return self.__engine
car = Car()
print(car.get_engine()) # Output: Private Engine
# print(car.__engine) # This would raise an AttributeError
# Accessing a protected attribute (not recommended)
car._protected = "New Value"
print(car._protected) # Output: New Value
3. Inheritance
Definition:
Inheritance allows a new class (child or subclass) to inherit attributes and methods from an existing class (parent or superclass). It promotes code reusability by allowing the child class to use or extend the functionality of the parent class.
Use-Case Example:
Inheritance is useful when creating a hierarchy of classes where a general class can serve as the base for more specific classes.
Syntax:
class ParentClass:
# Parent class attributes and methods
class ChildClass(ParentClass):
# Child class attributes and methods
Rules:
A child class can override or extend methods and attributes from the parent class.
Use the
super()
function to call the parent class’s constructor or methods.
Basic Example:
class Vehicle:
def __init__(self, brand):
self.brand = brand
def start(self):
return f"{self.brand} starting."
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.model = model
def start(self):
return f"{self.brand} {self.model} is starting."
car = Car("Toyota", "Corolla")
print(car.start()) # Output: Toyota Corolla is starting.
4. Polymorphism
Definition:
Polymorphism means "many forms." In Python, polymorphism allows objects of different classes to be treated as objects of a common base class. It enables a single interface to be used for different data types or classes.
Use-Case Example:
Polymorphism is used when different classes share a common interface or method, but implement it in different ways (e.g., multiple animals making different sounds).
Syntax:
class ClassName:
def method(self):
# Method implementation
# Different classes implementing the same method
Rules:
Polymorphism can be achieved through method overriding in inheritance.
Objects from different classes can be treated uniformly as long as they share the same method names.
Basic Example:
class Bird:
def fly(self):
return "Bird is flying."
class Plane:
def fly(self):
return "Plane is flying."
# Using polymorphism
def start_flight(flying_object):
return flying_object.fly()
bird = Bird()
plane = Plane()
print(start_flight(bird)) # Output: Bird is flying.
print(start_flight(plane)) # Output: Plane is flying.