Object-Oriented Programming (OOP) Concepts
Object-Oriented Programming (OOP) organizes software design around data, or objects, rather than functions and logic. Here’s an explanation of its core concepts with relatable examples!
1. Class
A class is a blueprint or template defining what an object should have.
Example: Imagine a blueprint of a house describing its size, rooms, and layout. It’s a guide to create actual houses.
class Car:
brand = "Toyota"
color = "Red"
2. Object
An object is a specific instance of a class.
Example: Using the house blueprint, you can build multiple houses. Each house is an object.
my_car = Car()
print(my_car.brand) # Output: Toyota
3. Encapsulation
Encapsulation hides an object’s details and provides access through methods.
Example: A TV remote allows you to change the channel without knowing how it works inside.
class BankAccount:
__balance = 0 # Private variable
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount()
account.deposit(100)
print(account.get_balance()) # Output: 100
4. Inheritance
Inheritance lets a class inherit properties and methods from another class.
Example: A smartphone inherits basic phone functionality and adds features like apps.
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Bark"
my_pet = Dog()
print(my_pet.sound()) # Output: Bark
5. Polymorphism
Polymorphism means one method can work differently based on the object.
Example: A power button behaves differently for a TV or a computer.
class Bird:
def fly(self):
return "Flies high"
class Penguin(Bird):
def fly(self):
return "Can't fly, but swims"
birds = [Bird(), Penguin()]
for bird in birds:
print(bird.fly())
6. Abstraction
Abstraction hides complex details and shows only the essentials.
Example: Driving a car requires only a steering wheel and pedals, not knowledge of how the engine works.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
return length * width
rect = Rectangle()
print(rect.area(5, 3)) # Output: 15

Comments
Post a Comment