Object-Oriented Programming in Python
Object-Oriented Programming in Python
def bark(self):
return f"{self.name} 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"
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 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()
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.