Latest posts

10/recent/ticker-posts

Concepts of OOP in Python | Object Oriented Programming in Python | Classes, objects, inheritance, Polymorphism, Encapsulation in Python

In the last post on Python programming, we learned about File Operations of Python Programming. You can simply watch this post by clicking on this link. Click Here
We have covered all the important topics regarding file operations. So in this post on Python Programming, we are going to learn about OOP's of Python Programming.

What is OOP :

Object-oriented programming (OOP) is a powerful paradigm that brings modularity, reusability, and encapsulation to Python programming. By organizing code into classes and objects, developers can efficiently structure their programs and create robust, scalable solutions. In this blog post, we will dive into the world of OOP in Python, covering key concepts such as classes, objects, inheritance, polymorphism, and encapsulation. We'll explore real-world examples, provide practical code snippets, and highlight the benefits of using OOP in your Python projects. By the end of this article, you'll have a solid understanding of OOP principles and be equipped to leverage its power in your own coding endeavors.

This post contains, only the overview of OOP concepts like Classes, objects, inheritance, polymorphism, and encapsulation.
In the next post on OOP, we are going to explore each concept of OOP in detail.

1. Introduction to OOP:

Object-oriented programming is a programming paradigm that revolves around the concept of objects, which are instances of classes. A class serves as a blueprint for creating objects, defining their attributes (variables) and behaviors (methods).
A method is a function inside a class, that is created to do a specific operation or a task. It can be callable by using the Object of their class. In Python, classes are defined using the class keyword.

Syntax :
class ClassName:
    # Class variables and attributes
    
    def __init__(self, arguments):
        # Constructor method
    
    def method_name(self, arguments):
        # Class methods

Let's break down the different components:
  1. The 'class' keyword is used to define a class.
  2. 'ClassName' is the name of the class. You can choose any valid name according to the Python naming conventions.
  3. Class variables and attributes can be defined within the class. These variables are shared among all instances of the class.
  4. The '__init__' method is a special method called the constructor. It is executed when a new instance of the class is created. You can define and initialize instance variables within this method.
  5. 'self' is a reference to the instance of the class. It is used to access instance variables and methods within the class.
  6. Other methods can be defined in the class. They typically operate on the instance variables and perform specific actions.
  7. Arguments can be passed to the methods and the constructor for performing operations or setting initial values.
Let's explore an Example :
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating an instance of the class
person1 = Person("Alice", 25)

# Accessing instance variables
print(person1.name)  # Output: Alice
print(person1.age)   # Output: 25

# Calling a class method
person1.greet()      # Output: Hello, my name is Alice and I am 25 years old.

Try Yourself...


In the above example, we defined a 'Person' class with an '__init__' method to initialize the 'name' and 'age' instance variables. The 'greet' method is defined to print a greeting message using the instance variables. We then created an instance of the 'Person' class, accessed its variables, and called the 'greet' method.

2. Inheritance and Polymorphism :

Inheritance is a fundamental concept in OOP that allows the creation of derived classes (child classes) from existing classes (parent classes). The child classes inherit the attributes and methods of their parent classes and can also define their own unique attributes and methods. This promotes code reuse and enables hierarchical relationships.

Syntax :
class ChildClass(ParentClass):
    # Child class attributes and methods

Example :
class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def accelerate(self):
        print(f"The {self.make} {self.model} is accelerating.")

class ElectricCar(Car):
    def __init__(self, make, model, battery_capacity):
        super().__init__(make, model)
        self.battery_capacity = battery_capacity

    def charge(self):
        print(f"The {self.make} {self.model} is charging.")
        print(f"Baterry capacity of {self.model} is {self.battery_capacity}")

electric_car1 = ElectricCar("Tesla", "Model S", "100 kWh")
electric_car1.accelerate()
electric_car1.charge()

Try Yourself...


In this example, we define an 'ElectricCar' class that inherits from the 'Car' class. The 'super()' function is used to invoke the parent class's '__init__' method. The 'ElectricCar' class also introduces a new method 'charge'.

So in the above example, we have seen a class 'Car' as a Parent class. which contains a constructor '__init__' that is created to initialize the attributes of the class. The 'self' is a reference to the instance of the class. It is used to access instance variables and methods within the class.
After that, we created a child class 'ElectricalCar', that inherits from the class 'Car'.
In the derived class 'ElectricCar' we have called the methods of class 'Car' using the 'Super' function inside the '__init__' method of the derived class 'ElectricCar'. And after that, again we have defined another attribute 'baterry_capacity' using the 'self' keyword.

Polymorphism is another powerful feature of OOP that allows objects of different classes to be used interchangeably. Polymorphism promotes code flexibility and extensibility.

Example :
class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def accelerate(self):
        print(f"The {self.make} {self.model} is accelerating.")

class ElectricCar(Car):
    def __init__(self, make, model, battery_capacity):
        super().__init__(make, model)
        self.battery_capacity = battery_capacity

    def charge(self):
        print(f"The {self.make} {self.model} is charging.")
        print(f"Baterry capacity of {self.model} is {self.battery_capacity}")

def perform_acceleration(car):
    car.accelerate()

car1 = Car("Toyota", "Camry")
electric_car1 = ElectricCar("Tesla", "Model S", "100 kWh")

perform_acceleration(car1)  # Output: The Toyota Camry is accelerating.
perform_acceleration(electric_car1) 

Try Yourself...


In this example, the 'perform_acceleration' function can accept objects of both the 'Car' class and the 'ElectricCar' class, demonstrating polymorphism.

3. Encapsulation and Access Modifiers:

Encapsulation is the practice of bundling data and methods within a class and controlling access to them. It helps protect the integrity of data and prevents unauthorized access. In Python, access to attributes and methods can be controlled using access modifiers: public, private, and protected.

  • Public access (default): Attributes and methods can be accessed from anywhere.
  • Private access: Attributes and methods are indicated by a double underscore prefix (e.g., __attribute) and can only be accessed within the class.
  • Protected access: Attributes and methods are indicated by a single underscore prefix (e.g., _attribute) and should be treated as internal to the class or its subclasses.

Syntax :
class ClassName:
    def __init__(self):
        self._private_attribute = 10
    
    def _private_method(self):
        # Method implementation

    def public_method(self):
        # Method implementation

In the above syntax, the '_private_attribute' and '_private_method' are intended to be treated as private, even though they can still be accessed from outside the class. The 'public_method' does not have any naming convention, indicating that it is intended to be accessed publicly.

Example :
class Person:
    def __init__(self, name, age):
        self.name = name  # public attribute
        self._age = age  # protected attribute
        self.__address = "123 Main St"  # private attribute

    def greet(self):
        print(f"Hello, my name is {self.name}.")

    def _get_age(self):
        return self._age

    def __get_address(self):
        return self.__address

person = Person("Alice", 25)
person.greet()
print(person.name)  # Output: Alice
print(person._get_age())  # Output: 25
print(person.__get_address())  # Error: AttributeError

Try Yourself...


In this example, we define a 'Person' class with the public, protected, and private attributes. The 'greet()' method is a public method, '_get_age()' is a protected method, and '__get_address()' is a private method. Accessing the private attribute or method from outside the class raises an 'AttributeError'.

Conclusion :

Object-oriented programming is a powerful paradigm in Python that promotes code organization, modularity, and reusability. By utilizing classes, objects, inheritance, polymorphism, and encapsulation, developers can create more structured and scalable programs.

In this blog post, we explored the fundamentals of object-oriented programming in Python. We covered the overviews of the concept of classes, objects, and their interactions, as well as inheritance, polymorphism, and encapsulation. By understanding these concepts, you'll be equipped to design and build sophisticated applications using OOP principles.

Remember, object-oriented programming is a vast topic with many advanced features and design patterns. Continually exploring and practicing OOP concepts will enhance your programming skills and enable you to create elegant and maintainable code.

So, dive into the world of OOP in Python, unleash its power, and elevate your programming capabilities to new heights!

In the next post on OOP in Python, we are going to learn more about Classes, Objects, and all other concepts of OOP in detail.

I hope this post will help you to learn Python programming more..!

Thank You...!




Also Visit


Post a Comment

0 Comments