Object-Oriented Programming (OOP) in Python
Python supports Object-Oriented Programming (OOP), which allows developers to organize code into objects that represent real-world entities. OOP makes programs more modular, reusable, and easier to maintain.
What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to design applications.
- Class → Blueprint for creating objects
- Object → An instance of a class
- Methods → Functions defined inside a class
- Attributes → Variables associated with a class or object
In short: OOP models real-world things in code.
1. Creating a Class and Object
Example
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(self.name, "is barking")
# Creating an object
my_dog = Dog("Buddy", "Labrador")
my_dog.bark()
Explanation
class Dog:defines a class named Dog.__init__is a constructor that initializes object data.selfrefers to the current object.my_dog = Dog("Buddy", "Labrador")creates an object.my_dog.bark()calls the method.
Output: Buddy is barking
2. Inheritance
Inheritance allows a class to inherit properties and methods from another class.
Example
class Animal:
def eat(self):
print("Eating")
class Cat(Animal):
def meow(self):
print("Meowing")
my_cat = Cat()
my_cat.eat()
my_cat.meow()
Explanation
Catinherits fromAnimal.my_catcan access methods of both classes.
Output
Eating
Meowing
3. Encapsulation
Encapsulation hides the internal details of an object and allows controlled access.
Example
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private attribute
def get_balance(self):
return self.__balance
account = BankAccount(1000)
print(account.get_balance())
Explanation
__balanceis a private variable.- It cannot be accessed directly outside the class.
get_balance()provides safe access.
Encapsulation protects data from unwanted access.
4. Polymorphism
Polymorphism allows one interface to be used for different types of objects.
Example
class Bird:
def sound(self):
print("Some bird sound")
class Parrot(Bird):
def sound(self):
print("Parrot says Squawk")
class Crow(Bird):
def sound(self):
print("Crow says Caw")
def make_sound(bird):
bird.sound()
make_sound(Parrot())
make_sound(Crow())
Explanation
- The same method
sound()behaves differently. - The function works for all bird objects.
Output
Parrot says Squawk
Crow says Caw
5. Advantages of OOP in Python
- Modularity → Code is organized into classes
- Reusability → Existing classes can be reused
- Maintainability → Easy to update and manage
- Real-world Modeling → Programs reflect real-world entities