Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is object oriented programming in Python

Understanding Object-Oriented Programming

When you're just starting out with programming, you might feel like you're learning a new language – because you are! Object-Oriented Programming, or OOP for short, is a way of writing programs that is based on the concept of "objects." These objects can be thought of as neat little packages that contain both data and the operations that can be performed on that data.

Imagine you have a real-life object, like a smartphone. A smartphone has data (like contact lists, messages, and photos) and operations or functionalities (like making calls, sending texts, and taking pictures). In OOP, we create digital versions of real-world objects like these, with their own data and functionalities.

The Pillars of Object-Oriented Programming

OOP is built on four main principles: encapsulation, abstraction, inheritance, and polymorphism. Let's break these down using simple terms and analogies.

Encapsulation: Your Personal Diary

Think of encapsulation like a personal diary. Your diary keeps your secrets (data) hidden from the world, and you have specific methods (like writing or reading) to interact with these secrets. In programming, encapsulation is about keeping the data within an object private and exposing only selected methods to access or modify that data.

Abstraction: The Car Dashboard

Abstraction is like the dashboard of a car. You don't need to know how the engine works to drive a car; you just need to know how to use the controls on the dashboard. Similarly, abstraction in OOP means exposing only the necessary components of an object to the outside world while hiding the complex details.

Inheritance: Family Traits

Inheritance can be compared to the way you might inherit traits from your parents. In OOP, a new object can inherit the properties and methods of an existing object. This helps to reduce code repetition and makes your code easier to maintain.

Polymorphism: The Swiss Army Knife

Polymorphism is like a Swiss Army knife. The same tool can take different forms (like a knife, a screwdriver, or a pair of scissors) depending on what you need at the moment. In OOP, polymorphism allows objects to be treated as instances of their parent class rather than their actual class, which means the same function can behave differently for different objects.

Objects and Classes in Python

In Python, everything is an object. But to create objects, we first need to define their blueprint, which is called a class. A class specifies what data and methods an object will have.

Defining a Class

Let's define a simple class to represent a dog.

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        return f"{self.name} says woof!"

Here, Dog is the class, and it has two data attributes: name and breed. It also has a method bark() which is an action the dog can perform.

Creating an Object

Once we have a class, we can create an object, or an instance of that class.

my_dog = Dog(name="Buddy", breed="Golden Retriever")
print(my_dog.bark())  # Outputs: Buddy says woof!

In this example, my_dog is an object of the class Dog, and we can access its method bark().

Encapsulation in Python

Encapsulation in Python can be achieved by using private attributes, which are denoted by double underscores.

class Account:
    def __init__(self, name, balance):
        self.name = name
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount

    def show_balance(self):
        return self.__balance

Here, __balance is a private attribute, and it can only be accessed or modified through the methods deposit() and show_balance().

Inheritance in Python

In Python, inheritance is straightforward. Let's create a class Bird and a subclass Parrot.

class Bird:
    def __init__(self, name):
        self.name = name

    def fly(self):
        return f"{self.name} can fly!"

class Parrot(Bird):
    def speak(self):
        return f"{self.name} can speak!"

The Parrot class inherits from Bird, which means it has all the attributes and methods of Bird plus any additional ones defined in Parrot.

my_parrot = Parrot(name="Polly")
print(my_parrot.fly())      # Outputs: Polly can fly!
print(my_parrot.speak())    # Outputs: Polly can speak!

Polymorphism in Python

Polymorphism is about using a unified interface to operate on objects of different classes. Let's see an example:

class Cat:
    def speak(self):
        return "Meow!"

class Dog:
    def speak(self):
        return "Woof!"

def animal_sound(animal):
    return animal.speak()

my_cat = Cat()
my_dog = Dog()

print(animal_sound(my_cat))  # Outputs: Meow!
print(animal_sound(my_dog))  # Outputs: Woof!

The function animal_sound takes an animal as a parameter and calls its speak method, regardless of the animal's type.

Conclusion: The Symphony of Objects

Object-Oriented Programming in Python can be likened to conducting a symphony. Each instrument (object) has its unique sound (data) and knows how to play its part (methods) in the orchestra. The conductor (you, the programmer) brings them together to create a harmonious piece (your program). As you write more code, you'll become more adept at creating and orchestrating these objects, producing programs that are not only functional but also elegant and easy to understand. Just like a well-conducted symphony, a well-designed OOP system can be a beautiful thing to behold. Happy coding!