DEV Community

Ankithajitwta
Ankithajitwta

Posted on

Oops concept in Python

I'm Ankitha working for Luxoft India, as a junior software engineer. I'm a developer and it is important to know the concepts of oops. So, here is an article about Oops.

Introduction:

Object-oriented programming (OOP) is a programming paradigm that focuses on creating objects that contain both data and methods to operate on that data. In Python, everything is an object, which makes it an ideal language for OOP. The four pillars of OOP are inheritance, encapsulation, abstraction, and polymorphism. In this answer, we will discuss each of these pillars in detail with an example.

Inheritance:

Inheritance is the process of creating new classes from existing ones. The base class is also called the parent class, and the new class is called the child class. In Python, we use the "class" keyword to define classes.

Here is an Example of Inheritance:

`class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species
    def speak(self):
        pass
class Dog(Animal):
    def __init__(self, name):
        super().__init__(name, "Dog")

    def speak(self):
        return "Woof!"

my_dog = Dog("Fido")
print(my_dog.name)
print(my_dog.species)
print(my_dog.speak())`
Enter fullscreen mode Exit fullscreen mode

In this example, we define a parent class "Animal" with an "init" method that initializes the name and species attributes. We also define a "speak" method that returns nothing. Then we define a child class "Dog" that inherits from the "Animal" class. We create an object of the "Dog" class and print its attributes and the result of its "speak" method.

Encapsulation:

Encapsulation ensures that the internal state of an object is not directly accessible from outside the object. In Python, we can achieve encapsulation by using private and protected attributes and methods.

Here is an Example for Encapsulation:

`class BankAccount:
    def __init__(self, balance):
        self._balance = balance

    def deposit(self, amount):
        self._balance += amount

    def withdraw(self, amount):
        if self._balance >= amount:
            self._balance -= amount
            return amount
        else:
            return "Insufficient funds"
my_account = BankAccount(1000)
print(my_account._balance)

my_account.deposit(500)
print(my_account.withdraw(2000))
print(my_account._balance)
`

Enter fullscreen mode Exit fullscreen mode

In this example, we define a class "BankAccount" with a "balance" attribute (which is protected by using a single underscore). We also define "deposit" and "withdraw" methods to modify the balance attribute. We create an object of the "BankAccount" class and try to access the balance attribute directly (which is not recommended). Then we deposit and withdraw some money and print the balance attribute (which is also not recommended).

Abstraction:

Abstraction is the process of hiding unnecessary implementation details of a class from its users. It ensures that the users of a class only see the essential features of the class. In Python, we can achieve abstraction by using abstract classes and methods.

Here is an Example of Abstraction:

def calculate_area(shape, dimensions):
    if shape == 'rectangle':
        return dimensions[0] * dimensions[1]
    elif shape == 'triangle':
        return 0.5 * dimensions[0] * dimensions[1]
    elif shape == 'circle':
        return 3.14 * dimensions[0] ** 2
    else:
        return None

Enter fullscreen mode Exit fullscreen mode

By using abstraction, we have created a simple, reusable function that can calculate the area of any shape without the need for separate functions for each type of shape. This makes the code more efficient and easier to maintain, as we only need to make changes to one function rather than multiple functions if a change is needed.

Polymorphism

Polymorphism in programming refers to the ability of objects to take on multiple forms or behaviors. In Python, polymorphism can be achieved through function overloading and method overriding.

Here is an example:

class Animal:
    def speak(self):
        print("Animal is speaking")

class Dog(Animal):
    def speak(self):
        print("Dog is barking")

class Cat(Animal):
    def speak(self):
        print("Cat is meowing")

def make_animal_speak(animal):
    animal.speak()

animal = Animal()
dog = Dog()
cat = Cat()
make_animal_speak(animal) 
make_animal_speak(dog) 
make_animal_speak(cat) 

Enter fullscreen mode Exit fullscreen mode

This demonstrates polymorphism in action - the make_animal_speak() function can work with any object that has a speak() method, regardless of its specific type, and the correct implementation of speak() is automatically called based on the object's type.

Conclusion:

In conclusion, Object-Oriented Programming (OOP) is a programming paradigm that focuses on creating objects that interact with each other to accomplish a specific task. OOP provides several benefits, including modularity, reusability, and extensibility.

The key concepts of OOP include encapsulation, inheritance, and polymorphism. Inheritance allows new classes to be based on existing classes, inheriting their properties and methods. Polymorphism allows objects to take on multiple forms or behaviors.

In OOP, code is organized into classes, which are templates for creating objects, and objects are instances of classes. Classes can also have properties, which are attributes of an object, and methods, which are functions that operate on the object.

Overall, OOP is a powerful paradigm for creating robust and scalable software applications that are easy to understand, maintain, and extend. It is widely used in many programming languages, including Python, Java, and C++.

Top comments (0)