Skip to content

Object Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm that is based on the concept of "objects," which can contain data (attributes) and code (methods). Python, being an object-oriented language, supports OOP principles including encapsulation, inheritance, polymorphism, and abstraction.

Core Concepts of OOP in Python

  1. Classes and Objects

    • A class is a blueprint for creating objects (instances).
    • An object is an instance of a class.

    Example:

    python
    class Dog:
        def __init__(self, name, age):
            self.name = name  # Attribute
            self.age = age    # Attribute
    
        def bark(self):  # Method
            print(f"{self.name} is barking!")
    
    # Creating an object (instance) of the class Dog
    my_dog = Dog("Buddy", 3)
    
    # Accessing attributes and methods
    print(my_dog.name)  # Output: Buddy
    my_dog.bark()       # Output: Buddy is barking!
  2. Encapsulation

    • Encapsulation is the concept of restricting access to certain components of an object, usually through private and public access modifiers.
    • In Python, we can "hide" attributes or methods by prefixing them with a double underscore (__), making them private.

    Example:

    python
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.__age = age  # Private attribute
    
        def get_age(self):  # Public method
            return self.__age
    
    p = Person("John", 30)
    print(p.name)  # Output: John
    print(p.get_age())  # Output: 30
    print(p.__age)  # AttributeError: 'Person' object has no attribute '__age'
  3. Inheritance

    • Inheritance allows a class to inherit attributes and methods from another class, promoting code reuse.
    • The class that inherits is called a child class, and the class from which it inherits is called the parent class.

    Example:

    python
    class Animal:
        def __init__(self, name):
            self.name = name
    
        def speak(self):
            raise NotImplementedError("Subclass must implement abstract method")
    
    class Dog(Animal):
        def speak(self):
            return f"{self.name} says Woof!"
    
    class Cat(Animal):
        def speak(self):
            return f"{self.name} says Meow!"
    
    dog = Dog("Rex")
    cat = Cat("Whiskers")
    
    print(dog.speak())  # Output: Rex says Woof!
    print(cat.speak())  # Output: Whiskers says Meow!
  4. Polymorphism

    • Polymorphism allows objects of different classes to be treated as objects of a common parent class. This can be achieved through method overriding, where a subclass provides its own implementation of a method defined in the parent class.

    Example:

    python
    class Bird:
        def fly(self):
            print("Bird is flying")
    
    class Airplane:
        def fly(self):
            print("Airplane is flying")
    
    def let_it_fly(flyable_object):
        flyable_object.fly()
    
    bird = Bird()
    plane = Airplane()
    
    let_it_fly(bird)   # Output: Bird is flying
    let_it_fly(plane)  # Output: Airplane is flying
  5. Abstraction

    • Abstraction involves hiding the complex implementation details and showing only the necessary features of an object. In Python, abstraction can be achieved by using abstract classes and methods from the abc module.

    Example:

    python
    from abc import ABC, abstractmethod
    
    class Shape(ABC):
        @abstractmethod
        def area(self):
            pass
    
    class Circle(Shape):
        def __init__(self, radius):
            self.radius = radius
    
        def area(self):
            return 3.14 * self.radius * self.radius
    
    class Square(Shape):
        def __init__(self, side):
            self.side = side
    
        def area(self):
            return self.side * self.side
    
    circle = Circle(5)
    square = Square(4)
    
    print(circle.area())  # Output: 78.5
    print(square.area())  # Output: 16

More Advanced OOP Concepts

  1. Method Overloading: Python does not support method overloading by default, but you can achieve similar functionality by using default arguments or variable-length argument lists.

    Example:

    python
    class Math:
        def add(self, a, b=0, c=0):
            return a + b + c
    
    obj = Math()
    print(obj.add(2))      # Output: 2
    print(obj.add(2, 3))   # Output: 5
    print(obj.add(2, 3, 4))  # Output: 9
  2. Magic Methods (Dunder Methods): These are special methods that Python calls automatically for certain operations. They are typically surrounded by double underscores (e.g., __init__, __str__, __len__).

    Example:

    python
    class Book:
        def __init__(self, title, author):
            self.title = title
            self.author = author
    
        def __str__(self):
            return f"'{self.title}' by {self.author}"
    
    book = Book("1984", "George Orwell")
    print(book)  # Output: '1984' by George Orwell
  3. Multiple Inheritance: In Python, a class can inherit from more than one class, allowing it to combine features from multiple parent classes.

    Example:

    python
    class A:
        def method_a(self):
            print("Method A")
    
    class B:
        def method_b(self):
            print("Method B")
    
    class C(A, B):
        def method_c(self):
            print("Method C")
    
    obj = C()
    obj.method_a()  # Output: Method A
    obj.method_b()  # Output: Method B
    obj.method_c()  # Output: Method C

Summary of OOP Concepts in Python:

  • Classes and Objects: Classes define blueprints for objects, which are instances of those classes.
  • Encapsulation: Hiding implementation details and restricting access to certain components.
  • Inheritance: A class can inherit methods and attributes from another class.
  • Polymorphism: Methods with the same name can behave differently depending on the object that invokes them.
  • Abstraction: Hiding complexity and exposing only essential parts of an object.

Python’s flexibility with OOP makes it easy to use object-oriented principles to create maintainable and reusable code.

J2J Institute private limited