Object-Oriented Programming in Python
Object-oriented programming (OOP) is a programming paradigm that uses "objects" to
design applications and computer programs. Python, being an object-oriented
language, allows developers to create classes and objects, which enhance code
reusability and organization.
Classes and Objects
A class in Python is essentially a blueprint for creating objects. It defines a set of
attributes and methods that the created objects will have. An object is an instance of a
class, containing data and behavior defined by the class. Here’s a basic example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
# Creating an object of the Dog class
my_dog = Dog("Buddy", 3)
print(my_dog.bark()) # Output: Buddy says woof!
In this example, the Dog class has an initializer method (__init__) that sets the name and
age of the dog, along with a method bark that returns a string when called.
Inheritance
Inheritance allows a class to inherit attributes and methods from another class. This
promotes code reusability. For example:
class Animal:
def speak(self):
return "Animal speaks"
class Cat(Animal): # Cat inherits from Animal
def speak(self):
return "Meow"
my_cat = Cat()
print(my_cat.speak()) # Output: Meow
In this case, the Cat class inherits from the Animal class, overriding the speak method to
provide its own implementation.
Encapsulation
Encapsulation is the bundling of data (attributes) and methods that operate on the data
into a single unit or class. It also restricts direct access to some of the object's attributes,
which can prevent unintended interference and misuse. This is often implemented using
private attributes:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # Output: 150
In this example, the __balance attribute is private, and it can only be accessed through
the deposit and get_balance methods.
Polymorphism
Polymorphism allows methods to do different things based on the object calling them,
even if they share the same name. For example:
class Bird:
def fly(self):
return "Flapping wings"
class Airplane:
def fly(self):
return "Using engines"
def make_fly(flyable):
print(flyable.fly())
parrot = Bird()
boeing = Airplane()
make_fly(parrot) # Output: Flapping wings
make_fly(boeing) # Output: Using engines
Here, both Bird and Airplane classes implement the fly method differently, demonstrating
polymorphism.
These core concepts of OOP—classes and objects, inheritance, encapsulation, and
polymorphism—enhance the structure and maintainability of Python code, making it
easier to manage and expand over time.