Python OOPS
Object-Oriented Programming (OOP) in Python
Object-oriented programming (OOP) is a programming paradigm that uses objects—collections of data and methods that operate on that data. In Python, everything is an object, and the language supports OOP principles. Key concepts in OOP include classes, objects, encapsulation, inheritance, and polymorphism.
Classes and Objects
A class is a blueprint for creating objects. An object is an instance of a class. Classes define attributes (data members) and methods (functions) that operate on the attributes.
Creating a Class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
# Creating an object (instance) of the class
my_dog = Dog(name="Buddy", age=3)
# Accessing attributes and calling methods
print(f"{my_dog.name} is {my_dog.age} years old.")
my_dog.bark()
Inheritance
Inheritance allows a class (subclass/derived class) to inherit the attributes and methods of another class (superclass/base class).
class Animal:
def __init__(self, species):
self.species = species
def make_sound(self):
print("Some generic sound")
class Cat(Animal):
def purr(self):
print("Purr")
# Creating objects
generic_animal = Animal(species="Unknown")
my_cat = Cat(species="Felis catus")
# Using inherited attributes and methods
print(generic_animal.species)
generic_animal.make_sound()
print(my_cat.species)
my_cat.make_sound()
my_cat.purr()
Encapsulation
Encapsulation restricts access to some of an object's components and can prevent the accidental modification of data.
class BankAccount:
def __init__(self, balance):
self._balance = balance # Protected attribute
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if amount <= self._balance:
self._balance -= amount
else:
print("Insufficient funds")
def get_balance(self):
return self._balance
# Creating an object
account = BankAccount(balance=1000)
# Using methods
account.deposit(500)
account.withdraw(200)
print(f"Current balance: {account.get_balance()}")
Polymorphism
Polymorphism allows objects to be treated as instances of their parent class.
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# Creating objects
rectangle = Rectangle(width=4, height=5)
circle = Circle(radius=3)
# Using polymorphism
shapes = [rectangle, circle]
for shape in shapes:
print(f"Area: {shape.area()}")
These are just basic examples to introduce OOP concepts in Python. In practice, OOP is used to design and organize complex systems, enhance code reusability, and model real-world entities with a clear structure.