Python OOP Concepts Tutorial

In Python, Object-Oriented Programming (OOP) represents a programming paradigm that provides a method for organizing code by encapsulating properties and behaviors within distinct objects. This approach enables programmers to represent real-world entities using classes, which serve as templates for creating objects.

Object Oriented Programming promotes modular design, scalability, and code reusability, simplifying the management of complex applications. As a language that embraces OOP principles, Python facilitates the effective organization of code via interactions among objects. This methodology improves code maintainability by arranging it in a coherent and hierarchical manner. OOP is extensively applied in various domains such as software development, game creation, graphical user interface applications, and data modeling, guaranteeing both flexibility and efficiency in programming.

The following are the main concepts of Object-Oriented Programming in Python:

  • Classes and Objects
  • Encapsulation
  • Inheritance
  • Abstraction
  • Polymorphism

Let's explore these ideas through the use of examples.

Classes and Objects in Python

Class: A class serves as a template for generating objects. It specifies a collection of attributes that define the characteristics of any object belonging to that class. Attributes such as data members (including class and instance variables) and methods can be accessed using dot notation.

Object: An object represents a specific instance of a class. It embodies a concrete realization of the class and contains its own data. For instance, an object referred to as car_one, which is part of the Car class, serves as an instance of that class. It is a distinct instance of a data structure as delineated by its class definition. An object consists of data members (including both class variables and instance variables) as well as methods.

Python Classes and Objects Example

Now, let’s delve into the idea of classes and objects by examining a straightforward example.

Example

Example

# creating a class

class Employer:

  def __init__(self, name, industry):

    self.name = name          # attribute

    self.industry = industry  # attribute

  def display_info(self):     # method

    print(f"Employer: {self.name} - {self.industry}")

# Creating an object

employer_one = Employer("Example", "Education")

employer_one.display_info()

Output:

Output

Employer: C# Tutorial - Education

Explanation:

In the preceding example, we established a class named Employer. Inside this class, we designed a constructor that initializes two properties: name and industry. Additionally, we implemented a method called display_info to output the information pertaining to the Employer.

Subsequently, we instantiated an object of the Employer class by providing values for both the name and the industry attributes. We then invoked the display_info method to output the details of the Employer that were supplied.

For further information regarding Classes and Objects, please refer to: Python Objects Classes

Encapsulation in Python

Encapsulation is a fundamental concept in Object-Oriented Programming (OOP) that pertains to the grouping of attributes and methods within a singular class.

It limits direct access to information and facilitates regulated alterations via methods. This approach also aids in achieving data encapsulation.

In Python, encapsulation can be accomplished through the use of private attributes, which are defined by prefixing variables with a double underscore (__).

Python Encapsulation Example

Now, let us examine a straightforward illustration that demonstrates the concept of encapsulation in Python.

Example

Example

# creating a class

class Employer:

    def __init__(self, employee_count):

        self.__employee_count = employee_count  # Private attribute (name mangling)

    def get_employee_count(self): # method

        return self.__employee_count  # Accessing private attribute via method

# creating an object

employer_one = Employer(1500)

print("No. of Employees:", employer_one.get_employee_count())

# print("No. of Employees:", employer_one.__employee_count) # Trying to access private attribute directly (returns Error)

# Name Mangling

print("No. of Employees (Accessing via Name Mangling):", employer_one._Employer__employee_count) # Accessing via name mangling

Output:

Output

No. of Employees: 1500

No. of Employees (Accessing via Name Mangling): 1500

Explanation:

In the preceding illustration, we established the Employer class, which includes a private attribute known as _employeecount. Subsequently, we implemented a method to retrieve the count of employees. An instance of the Employer class was then generated, and we invoked the class method to display the employee count. Additionally, an attempt was made to access the private attribute directly, resulting in an error. Consequently, we employed name mangling techniques to access the attribute.

For additional insights on Encapsulation, please explore: Encapsulation in Python

Inheritance in Python

Inheritance represents a fundamental concept in Object-Oriented Programming (OOP) that enables a class, often referred to as a child class, to inherit attributes and behaviors from another class, known as the parent class. This mechanism facilitates a structured hierarchy and enhances the reusability of code across different classes.

Python Inheritance Example

Let's examine a straightforward example that illustrates how inheritance functions in Python.

Example

Example

# creating a class (parent class)

class Vertebrate:

    def __init__(self, name):

        self.name = name

        self.spine = True

    def move(self):

        print(f"{self.name} is moving.")

# creating another class (child class)

class Mammal(Vertebrate):

    def __init__(self, name, fur_color):

        super().__init__(name)

        self.fur_color = fur_color

    def nurse(self):

        print(f"{self.name} is nursing its young.")

# creating another class (child class)

class Bird(Vertebrate):

    def __init__(self, name, wingspan):

        super().__init__(name)

        self.wingspan = wingspan

    def fly(self):

        print(f"{self.name} is soaring through the air.")

# creating an object of Mammal class

dog = Mammal("Bear", "brown")

dog.move()

dog.nurse()

print("Spine Exist?:", dog.spine)

# creating an object of Bird class

eagle = Bird("Eagle", 2)

eagle.move()

eagle.fly()

print("Spine Exist?:", eagle.spine)

Output:

Output

Bear is moving.

Bear is nursing its young.

Spine Exist?: True

Eagle is moving.

Eagle is soaring through the air.

Spine Exist?: True

Explanation:

In the preceding example, we established a base class named Vertebrate, featuring public attributes such as name and spine, with the spine attribute initialized to True. Furthermore, we implemented a method called move. Subsequently, we developed two derived classes, Mammal and Bird, which inherit the attributes and methods from the Vertebrate class. In addition, we defined various methods specific to the child classes.

Finally, we have instantiated the objects from the child classes and attempted to access various attributes and methods. Consequently, both objects are able to effortlessly utilize the attributes and methods defined in the child classes, in addition to those from the parent class.

To gain further insights into the concept of Inheritance, please refer to: Inheritance in Python

Abstraction

Abstraction represents a fundamental concept in object-oriented programming (OOP), which enables the concealment of internal implementation specifics while exposing only the essential functionalities. The primary objective of abstraction is to shift our attention towards "what needs to be accomplished" instead of "how to accomplish it."

Python Abstraction Example

Let us examine a straightforward example that illustrates how abstraction functions in Python.

Example

Example

# importing the ABC class and abstractmethod decorator from abc module

from abc import ABC, abstractmethod

# creating a class

class Three_Dimensional_Shapes(ABC):

  @abstractmethod

  def calc_volume(self):

    pass

# creating another class to implement abstraction

class Cube(Three_Dimensional_Shapes):

  def __init__(self, side_length):

    self.side_length = side_length

  def calc_volume(self):

    return self.side_length ** 3

# creating an object of Cube class

side_length = 6

cube = Cube(side_length)

# printing the results

print("Cube's Side:", side_length)

print("Cube's Volume:", cube.calc_volume())

Output:

Output

Cube's Side: 6

Cube's Volume: 216

Explanation:

In the example provided, we have brought in the ABC class along with the abstractmethod decorator from the abc module. Subsequently, a class has been created that derives from the ABC class, and within it, an abstract method has been established. Following this, another class has been crafted that inherits from the base class and has overridden the method to produce the desired output.

For further information regarding Abstraction, please refer to: Abstraction in Python

Polymorphism in Python

Polymorphism is a crucial concept in Object-Oriented Programming (OOP) that essentially signifies having multiple forms. This principle enables methods to share the same name, but their functionality varies depending on the context of the object involved. Polymorphism can be realized through two main techniques: method overriding and method overloading.

Python Polymorphism Example

Let us examine the subsequent example that demonstrates the functionality of polymorphism in Python.

Example

Example

# creating a base class

class Vertebrate:

    def __init__(self, name):

        self.name = name

    def move(self):

        print(f"{self.name} moves in a generic way.")

# creating a child class

class Mammal(Vertebrate):

    def move(self):   # method overriding

        print(f"{self.name} walks.")

# creating a child class

class Bird(Vertebrate):

    def move(self):   # method overriding

        print(f"{self.name} flies.")

# creating object as a list

animals = [Vertebrate("Generic Vertebrate"), Mammal("Dog"), Bird("Eagle")]

for animal in animals:

    animal.move()

Output:

Output

Generic Vertebrate moves in a generic way.

Dog walks.

Eagle flies.

Explanation:

In the preceding example, we established a foundational class named Vertebrate, which includes a public attribute labeled name. Additionally, we defined a method called move. Following this, we developed two derived classes, Mammal and Bird, which inherit the characteristics and methods from the Vertebrate class. In this context, we have overridden the move method in both classes to produce the desired output.

For further information on Polymorphism, please refer to: Polymorphism in Python

Advantages of OOPs over Procedural Programming

The Object-oriented Programming (OOP) has various advantages over the procedure-oriented programming. Some of them are discussed below:

  • OOP makes development and maintenance easier; whereas in procedural programming, managing code becomes difficult as the project size grows.
  • OOP enables data hiding; whereas in procedural programming, global data can be accessed from anywhere.
  • OOP provides the ability to simulate real-world events much more effectively. We can provide the solution of real word problems using OOP.
  • Conclusion

In this guide, we explored how Object-Oriented Programming (OOP) in Python serves as a robust paradigm that facilitates the organization and structuring of code by utilizing real-world concepts such as classes and objects. This approach enhances modularity, encourages code reusability, and improves data security through fundamental principles including encapsulation, abstraction, inheritance, and polymorphism. By representing programs as interacting objects, OOP simplifies the processes of maintenance, scaling, and extension, particularly in the context of large and intricate applications.

OOPs Concepts in Python - MCQs

  1. Which of the following is used to create an object in Python?
  • class
  • object
  • ClassName
  • new ClassName
  1. Which OOP principle is being followed when child classes inherit features from a parent class?
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation
  1. What is encapsulation in Python?
  • Hiding the class itself
  • Restricting access to parts of an object
  • Creating many objects
  • Using multiple classes
  1. Which keyword is used to define a class in Python?
  • class
  • define
  • object
  • function
  1. What is the term for using the same function name with different behavior in different classes?
  • Inheritance
  • Overloading
  • Encapsulation
  • Polymorphism

Input Required

This code uses input(). Please provide values below: