Object-Oriented Programming (OOP) is one the most powerful paradigms in Python. It allows you to model real-world entities into code by creating objeccts that encapsulate both data (attributes) and behavior (methods). Python makes OOP intuitive and flexible, which is why it's widely used in large-scale applications.
OOP is a programming approach based on the concept of objects.
For example:
color
, model
, and methods like drive()
or brake()
.__init__
) – A special method that initializes objects attributes.
class Car:
def __init__(self, brand, color):
self.brand = brand # attribute
self.color = color
def drive(self):
return f"The {self.color} {self.brand} is driving!"
# Create an object
my_car = Car("Toyota", "Red")
print(my_car.drive())
The Red Toyota is driving!
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private attribute
def deposite(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
Here, __balance
is hidden from outside access (private).
Promotes code reusability.
class Animal:
def sound(self):
return "This animal makes a sound."
class Dog(Animal): # Dog inherites from animal
def sound(self):
return "Bark!"
dog = Dog()
print(dog.sound())
Output:
Bark!
Same method name but different behaviour depending on the class.
class Bird:
def fly(self):
return "Some birds can fly."
class Penquin(Bird):
def fly(self):
return "Penquins cannot fly."
penquin = Penquin()
print(penquin.fly())
Output:
Penguins cannot fly.
Achieved in Python using abstract base classess (abc
module).
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
circle = Circle(5)
print(circle.area())
Output:
Area = 78.5
Python classes have built-in methods that start and end with __
.
Examples:
__init__()
→ Constructor__str__()
→ String representation__len__()
→ Length representation
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"Book: {self.title}"
def __len__(self):
return self.pages
b = Book("Python Basics", 250)
print(b) # Book: Python Basics
print(len(b)) # 250
🔹 Real-Life Example of OOP
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def get_details(self):
return f"Student: {self.name}, Grade: {self.grade}"
class GraduateStudent(Student):
def __init__(self, name, grade, degree):
super().__init__(name, grade)
self.degree = degree
def get_details(self):
return f"Student: {self.name}, Grade: {self.grade}, Degree: {self.degree}"
s1 = GraduateStudent("John", "A", "B.tech")
print(s1.get_details())
Output:
Student: John, Grade: A, Degree: B.tech
Leave a Reply