Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP)

1. Introduction to OOP

  • Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which can contain data (attributes) and methods (functions).
  • Benefits of OOP:
    • Code reusability through inheritance.
    • Better organization with encapsulation.
    • Enhanced functionality using polymorphism.

2. Key OOP Concepts in Python

  • Class: Blueprint for creating objects.
  • Object: Instance of a class.
  • Attributes: Variables that belong to an object.
  • Methods: Functions that belong to a class.

3. Defining Classes and Creating Objects

  • Example of a class:pythonCopy code
Python
class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

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

# Creating an object
my_car = Car("Toyota", "Corolla")
my_car.display_info()

4. The __init__ Method

  • Special method called a constructor, used for initializing object attributes.
  • Example:
Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name}.")

p1 = Person("Alice", 25)
p1.greet()

5. Inheritance

  • A mechanism to create a new class (child class) based on an existing class (parent class).
  • Example:
Python
class Animal:
    def speak(self):
        print("Animal speaks.")

class Dog(Animal):
    def speak(self):
        print("Dog barks.")

my_dog = Dog()
my_dog.speak()  # Output: Dog barks.

6. Encapsulation

  • Restricts access to certain attributes or methods to prevent unauthorized modifications.
  • Use underscores _ or __ to define private attributes.pythonCopy code
Python
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
print(account.get_balance())  # Output: 1000

7. Polymorphism

  • The ability of different classes to be treated as instances of the same class through shared methods.
  • Example
Python
class Bird:
    def fly(self):
        print("Bird is flying.")

class Penguin(Bird):
    def fly(self):
        print("Penguins can't fly.")

for bird in [Bird(), Penguin()]:
    bird.fly()

8. Working with super()

  • The super() function allows access to the methods of the parent class.
Python
class Vehicle:
    def __init__(self, brand):
        self.brand = brand

class Bike(Vehicle):
    def __init__(self, brand, model):
        super().__init__(brand)
        self.model = model

9. Special (Magic) Methods

  • Python provides special methods like __str__, __repr__, and more
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

Leave a Comment

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

Scroll to Top