Monday, 24 February 2025

Object Oriented Programming in Python

Unit 4 

Object-Oriented Programming (OOP) in Python

1. What is Object-Oriented Programming?

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects and classes. It helps in structuring complex programs by organizing data (attributes) and behavior (methods) into objects.


2. Key OOP Concepts in Python

OOP Concept

Description

Example

Class

A blueprint for creating objects

class Car:

Object

An instance of a class

my_car = Car()

Encapsulation

Hiding data using private/protected members

self.__speed = 50

Inheritance

One class can inherit properties of another

class SportsCar(Car)

Polymorphism

Different classes can have methods with the same name

def start_engine() in multiple classes

Abstraction

Hiding implementation details from users

from abc import ABC, abstractmethod


3. Creating Classes and Objects

a) Defining a Class

A class is a blueprint for creating objects. It defines attributes and methods.

python

class Car:

    def __init__(self, brand, model, year):

        self.brand = brand

        self.model = model

        self.year = year

 

    def display_info(self):

        return f"{self.year} {self.brand} {self.model}"

b) Creating Objects (Instances)

An object is an instance of a class.

python

car1 = Car("Toyota", "Corolla", 2022)

car2 = Car("Honda", "Civic", 2023)

 

print(car1.display_info())  # Output: 2022 Toyota Corolla

print(car2.display_info())  # Output: 2023 Honda Civic


4. Encapsulation (Data Hiding)

Encapsulation restricts access to certain attributes using private (__) and protected (_) members.

python

class BankAccount:

    def __init__(self, balance):

        self.__balance = balance  # Private variable

 

    def deposit(self, amount):

        self.__balance += amount

 

    def get_balance(self):

        return self.__balance

 

# Creating object

account = BankAccount(1000)

account.deposit(500)

print(account.get_balance())  # Output: 1500

 

# Accessing private variable (will cause an error)

# print(account.__balance)  # AttributeError


5. Inheritance (Code Reusability)

Inheritance allows one class to inherit attributes and methods from another class.

a) Single Inheritance

python

class Animal:

    def sound(self):

        return "Some generic sound"

 

class Dog(Animal):

    def sound(self):  # Method overriding

        return "Bark"

 

dog = Dog()

print(dog.sound())  # Output: Bark

b) Multiple Inheritance

A child class can inherit from multiple parent classes.

python

class A:

    def method_A(self):

        return "Method from Class A"

 

class B:

    def method_B(self):

        return "Method from Class B"

 

class C(A, B):

    pass

 

obj = C()

print(obj.method_A())  # Output: Method from Class A

print(obj.method_B())  # Output: Method from Class B


6. Polymorphism (Different Behavior for the Same Method)

Polymorphism allows different classes to have the same method name with different implementations.

a) Method Overriding

python

class Shape:

    def area(self):

        return 0

 

class Circle(Shape):

    def __init__(self, radius):

        self.radius = radius

 

    def area(self):

        return 3.14 * self.radius * self.radius

 

circle = Circle(5)

print(circle.area())  # Output: 78.5

b) Method Overloading (Using Default Arguments)

Python does not support method overloading directly, but it can be achieved using default parameters.

python

class Math:

    def add(self, a, b, c=0):

        return a + b + c


math_obj = Math()

print(math_obj.add(2, 3))      # Output: 5

print(math_obj.add(2, 3, 4))   # Output: 9


7. Abstraction (Hiding Implementation)

Abstraction hides the implementation details from users using abstract classes.

python

from abc import ABC, abstractmethod

 

class Animal(ABC):

    @abstractmethod

    def make_sound(self):

        pass  # Abstract method

 

class Dog(Animal):

    def make_sound(self):

        return "Woof!"

 

dog = Dog()

print(dog.make_sound())  # Output: Woof!


8. Special Methods (__str__, __repr__, etc.)

Python has special methods (also called dunder methods) that define object behavior.

python

class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age

 

    def __str__(self):

        return f"Person({self.name}, {self.age})"

 

p = Person("Alice", 30)

print(p)  # Output: Person(Alice, 30)

Other special methods include:

  • __init__() → Constructor
  • __del__() → Destructor
  • __len__() → Defines behavior for len()
  • __getitem__() → Defines behavior for indexing

9. Summary

  • Classes define objects and their behavior.
  • Encapsulation hides data using private/protected members.
  • Inheritance enables reusability by deriving new classes from existing ones.
  • Polymorphism allows different classes to have the same method name.
  • Abstraction hides implementation details using abstract classes.
  • Special methods (__str__, __len__) customize object behavior.

 

No comments:

Post a Comment

Desktop Virtualisation

Desktop Virtualization ( DV ) Desktop Virtualization ( DV ) is a technique that creates an illusion of a desktop provided to the user. It d...