Python Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm that uses “objects” to design applications and organize code. Python supports OOP principles such as encapsulation, inheritance, and polymorphism. Let’s explore OOP concepts with code examples:
1. Defining a Class
A class is a blueprint for creating objects. It defines attributes (data) and methods (functions) that the objects of the class will have.
python
# Class definition
class Person:
# Constructor method (initialize object)
def __init__(self, name, age):
self.name = name
self.age = age
# Method to display information about the person
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Creating objects (instances) of the Person class
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Accessing object attributes and methods
person1.display_info() # Output: Name: Alice, Age: 30
person2.display_info() # Output: Name: Bob, Age: 25
2. Encapsulation
Encapsulation refers to bundling the data (attributes) and methods (functions) that operate on the data into a single unit (class). This protects the data from direct access outside the class and allows controlled access through methods.
python
class BankAccount:
def __init__(self, account_number, balance):
self.account_number = account_number
self.__balance = balance # Private attribute (encapsulation)
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds!")
def display_balance(self):
print(f"Account Number: {self.account_number}, Balance: ${self.__balance}")
# Creating an instance of BankAccount
account1 = BankAccount("123456789", 1000)
# Accessing and modifying balance using methods
account1.display_balance() # Output: Account Number: 123456789, Balance: $1000
account1.deposit(500)
account1.display_balance() # Output: Account Number: 123456789, Balance: $1500
account1.withdraw(200)
account1.display_balance() # Output: Account Number: 123456789, Balance: $1300
3. Inheritance
Inheritance allows a class (subclass) to inherit attributes and methods from another class (superclass). It promotes code reusability and establishes an “is-a” relationship between classes.
python
# Base class (superclass)
class Animal:
def __init__(self, species):
self.species = species
def sound(self):
pass # Abstract method
# Derived class (subclass) inheriting from Animal
class Dog(Animal):
def __init__(self, name, breed):
super().__init__("Dog")
self.name = name
self.breed = breed
def sound(self):
return "Woof!"
# Creating an instance of Dog
dog1 = Dog("Buddy", "Labrador")
print(f"{dog1.name} is a {dog1.species} of breed {dog1.breed}.")
print(f"{dog1.name} says: {dog1.sound()}") # Output: Buddy says: Woof!
4. Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables methods to be called on objects without knowing their specific type, promoting flexibility and code extensibility.
python
# Base class
class Shape:
def area(self):
pass # Abstract method
# Derived classes (subclasses) implementing area method
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return math.pi * self.radius ** 2
# Function using polymorphism to calculate areas of shapes
def calculate_area(shape):
return shape.area()
# Creating instances of Rectangle and Circle
rectangle = Rectangle(5, 10)
circle = Circle(7)
# Calculating and displaying areas using polymorphism
print("Area of Rectangle:", calculate_area(rectangle)) # Output: Area of Rectangle: 50
print("Area of Circle:", calculate_area(circle)) # Output: Area of Circle: 153.93804002589985
These examples demonstrate key concepts of Object-Oriented Programming (OOP) in Python, including class definition, encapsulation, inheritance, and polymorphism. Experiment with these concepts to understand how to design and implement object-oriented solutions in Python effectively.