Skip to content

OOPs In Python

Object-Oriented Programming (OOP) is a programming paradigm that uses objects, which are instances of classes, to structure code. In Python, everything is an object, and the language supports the four main principles of OOP:

  1. Encapsulation: The bundling of data (attributes) and methods (functions) that operate on the data into a single unit, known as a class.
  2. Abstraction: The concept of hiding complex implementation details and exposing only the necessary functionalities. Users interact with objects without needing to understand their internal workings.
  3. Inheritance: The mechanism by which a new class (subclass or derived class) can inherit attributes and methods from an existing class (base class or superclass).
  4. Polymorphism: The ability of objects of different classes to be treated as objects of a common base class, allowing for flexibility in code design.

Example:

        
# Creating a class
class Animal:
    def __init__(self, name):
        self.name = name

    def make_sound(self):
        pass  # Placeholder for method to be overridden


# Inheriting from the Animal class
class Dog(Animal):
    def make_sound(self):
        return "Woof!"


class Cat(Animal):
    def make_sound(self):
        return "Meow!"


# Creating objects
dog = Dog("Buddy")
cat = Cat("Whiskers")

# Using polymorphism
animals = [dog, cat]
for animal in animals:
    print(f"{animal.name} says: {animal.make_sound()}")
        
    

The provided Python code demonstrates OOP principles with a base class Animal and two derived classes Dog and Cat. Objects of these classes exhibit polymorphic behavior, and the code outputs the sound each animal makes.


Key Concepts:

  • Class: A blueprint for creating objects.
  • Object: An instance of a class with specific attributes and behaviors.
  • Constructor: Special method (`__init__`) called when an object is created.
  • The `self` Parameter: Reference to the instance of the class.
  • Instance Attribute: Variable representing the object's characteristics.
  • Method: Function defined within a class, operating on instance attributes.

Example:

        
# Define a class named 'Person'
class Person:
    # Constructor (initializes instance attributes)
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method
    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

# Create an object (instance) of the 'Person' class
person1 = Person("Alice", 30)

# Access instance attributes
name_of_person1 = person1.name
age_of_person1 = person1.age

# Call an instance method
greeting_of_person1 = person1.greet()
        
    

Output:

        
# Accessing instance attributes
name_of_person1 = "Alice"
age_of_person1 = 30

# Output of the instance method
greeting_of_person1 = "Hello, my name is Alice and I am 30 years old."