Skip to content
On this page

Object-Oriented Programming (OOP)

Classes and Objects:

Classes are blueprints for creating objects, which are instances of a class.

python
# Class definition
class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

Constructor and Destructor:

The constructor __init__() is used to initialize object properties, and the destructor __del__() is used to clean up resources when the object is destroyed.

python
# Constructor and Destructor
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __del__(self):
        print(f"{self.name} object is destroyed.")

Inheritance:

Inheritance allows a class to inherit properties and methods from another class.

python
# Inheritance
class Animal:
    def speak(self):
        return "Animal sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

Encapsulation and Abstraction:

Encapsulation hides the internal implementation details of an object, and abstraction provides a simplified interface for interacting with the object.

python
# Encapsulation and Abstraction
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount

    def get_balance(self):
        return self.__balance

Polymorphism:

Polymorphism allows objects of different classes to be treated as objects of the same class.

python
# Polymorphism
class Cat:
    def speak(self):
        return "Meow!"

class Duck:
    def speak(self):
        return "Quack!"

def animal_sound(animal):
    return animal.speak()