classes

Understanding Classes and Objects in Python

Python is an object-oriented programming (OOP) language, meaning it revolves around the concept of classes and objects. These help in organizing and structuring code efficiently. In this blog, we will explore classes, objects, and important OOP principles like Encapsulation, Inheritance, Polymorphism, and Abstraction with examples.

Table of Contents

What is a Class and an Object?

A class is a blueprint for creating objects. It defines attributes (variables) and behaviors (methods) that the objects will have.

An object is an instance of a class. It is a real-world entity that holds data and can perform actions.

Example:

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def show_details(self):
        print(f"Car: {self.brand} {self.model}")

# Creating objects
car1 = Car("Toyota", "Corolla")
car2 = Car("Honda", "Civic")

car1.show_details()
car2.show_details()

Output:
Car: Toyota Corolla
Car: Honda Civic

Constructor (__init__) and self

  • The constructor method (__init__) initializes an object’s attributes when it is created.
  • The keyword self represents the instance of the class and allows access to instance attributes.

OOP Principles in Python

1. Encapsulation

Encapsulation means hiding data inside a class and making it accessible only through methods. It prevents accidental modification of data.

Example:

class BankAccount:
    def __init__(self, account_number, balance):
        self.account_number = account_number
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount
        print(f"Deposited {amount}. New balance: {self.__balance}")

    def get_balance(self):
        return self.__balance

# Creating object
account = BankAccount("12345", 5000)
account.deposit(2000)
print("Balance:", account.get_balance())


Output:
Deposited 2000. New balance: 7000
Balance: 7000

Here, __balance is private and can only be accessed using methods.

2. Inheritance

Inheritance allows one class to inherit properties and methods from another class. It promotes code reuse.

Example:

class Animal:
    def sound(self):
        print("Animals make different sounds")

class Dog(Animal):
    def sound(self):
        print("Dog barks")

# Creating objects
dog = Dog()
dog.sound()

Ouput:
Dog barks

Here, the Dog class inherits from Animal but overrides the sound() method.

3. Polymorphism

Polymorphism means one method with different behaviors depending on the class.

Example:

class Bird:
    def fly(self):
        print("Birds can fly")

class Penguin(Bird):
    def fly(self):
        print("Penguins cannot fly")

# Function demonstrating polymorphism
def show_flying_ability(bird):
    bird.fly()

# Creating objects
sparrow = Bird()
penguin = Penguin()

show_flying_ability(sparrow)
show_flying_ability(penguin)

Output:
Birds can fly
Penguins cannot fly

Here, both classes have a fly() method, but their behavior is different.

4. Abstraction

Abstraction means hiding unnecessary details and showing only important features.

Example:

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

# Creating object
circle = Circle(5)
print("Circle Area:", circle.area())

Output:
Circle Area: 78.5

Here, Shape is an abstract class with an area() method that must be implemented in child classes.

Conclusion

  • Classes and objects help in structuring Python programs.
  • Encapsulation protects data.
  • Inheritance enables code reuse.
  • Polymorphism allows different implementations of the same method.
  • Abstraction hides unnecessary details.

Understanding these concepts will make your Python programming more efficient and structured!

Leave a Comment

Your email address will not be published. Required fields are marked *