Procedural vs Object-Oriented Programming Languages

Published Aug. 3, 2023, 11:02 a.m.

Programming paradigms play a significant role in how we design and structure our code. Two common paradigms are procedural programming and object-oriented programming (OOP). Let's explore their characteristics and differences:

Procedural Programming

Procedural programming follows a sequential approach, where a list of instructions is executed step by step.

Characteristics:

  • Works with functions that are organized in a linear fashion.
  • Can become difficult to maintain in large projects as the codebase grows.
  • Lacks real-world simulation, as it divides tasks into small functions.

Examples of Procedural Languages:

  1. C
  2. Fortran
  3. Pascal
  4. Visual Basic

Object-Oriented Programming

Object-oriented programming is an approach to problem-solving where computation is organized using objects.

Characteristics:

  • Emphasizes modularity and reusability, making development and maintenance easier.
  • Simulates real-world entities, enabling easy problem resolution through abstraction and modeling.
  • Provides data hiding through encapsulation, enhancing security as private data cannot be accessed from outside the class.

Examples of Object-Oriented Programming Languages:

  1. C++
  2. Java
  3. .NET
  4. Python
  5. C#

Python Object-Oriented Programming System (OOPS)

Python is a versatile object-oriented programming language. In Python, everything is an object, including classes, objects, functions, methods, and modules. These objects can be passed as arguments to functions or assigned to variables.

OOPS Principles

Object-Oriented Programming System (OOPS) adheres to several principles, which define its core concepts:

  1. Inheritance: Classes can inherit attributes and behaviors from other classes, promoting code reuse and hierarchy.
  2. Polymorphism: The ability of objects to take on multiple forms, allowing different objects to respond to the same method call differently.
  3. Abstraction: Hiding the complexity of objects and exposing only relevant functionalities to the outside world.
  4. Encapsulation: Wrapping data and methods together as a single unit, controlling access to the data through well-defined interfaces.

What is a Class

In Python, a class is a blueprint or plan to create objects. A class allows us to define the properties (attributes) and actions (behaviors) of an object.

How to Define a Class:

A class in Python is defined using the class keyword, followed by the class name and a colon. The class body contains instance variables, static and local variables, as well as instance methods, static methods, and class methods.

class ClassName:
    '''documentation string'''
    variables: instance variables, static and local variables
    methods: instance methods, static methods, class methods

The documentation string represents a description of the class and is optional. We can retrieve the doc string using two methods:

print(className.__doc__)
help(className)

Example 1: Car Class

Let's create a Car class that represents the properties and actions of a car object.

class Car:
    '''This class represents a car object'''
    # Instance Variables
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    # Instance Method
    def start(self):
        return f"{self.make} {self.model} is starting."

    # Instance Method
    def stop(self):
        return f"{self.make} {self.model} has stopped."

# Creating Car Objects
car1 = Car("Toyota", "Corolla", 2022)
car2 = Car("Honda", "Civic", 2023)

# Accessing Properties and Methods
print(car1.make)  # Output: Toyota
print(car2.model) # Output: Civic
print(car1.start()) # Output: Toyota Corolla is starting.
print(car2.stop())  # Output: Honda Civic has stopped.

Example 2: MathOperations Class

Now, let's create a MathOperations class that performs basic arithmetic operations.

class MathOperations:
    '''This class performs basic arithmetic operations'''

    # Static Method
    @staticmethod
    def add(a, b):
        return a + b

    # Static Method
    @staticmethod
    def subtract(a, b):
        return a - b

    # Class Method
    @classmethod
    def multiply(cls, a, b):
        return a * b

# Using Static and Class Methods
result1 = MathOperations.add(5, 3)          # Output: 8
result2 = MathOperations.subtract(10, 4)    # Output: 6
result3 = MathOperations.multiply(2, 6)     # Output: 12

print(result1, result2, result3)

In this example, the Car class has instance variables (make, model, and year) and instance methods (start() and stop()). Output: 8 6 12

What is an Object:

An object is a fundamental concept in object-oriented programming. It can be defined as a collection of data and its associated functionality. In simpler terms, an object represents a real-world entity that possesses both states (properties) and behaviors (functionalities).

Properties of an Object: The properties of an object refer to its state. There are two types of properties:

  1. Common-Static Properties: These properties are shared among all objects of the same class and remain the same for all instances.
  2. Specific-Dynamic Properties: These properties vary from one object to another and can change over time based on the object's behavior.

Behaviors of an Object: The behaviors of an object refer to its functionalities. Similar to properties, there are two types of behaviors:

  1. Common-Static Behaviors: These behaviors are shared among all objects of the same class and remain the same for all instances.
  2. Specific-Dynamic Behaviors: These behaviors are unique to each object and can be altered or invoked based on specific circumstances.

Example:

Let's consider two examples of objects to better understand the concept:

  1. Object1: Human

    • Identity: Amar
    • Properties: Color, Height, Weight
    • Functionalities: walk(), see(), run(), ...
  2. Object2: Animal

    • Identity: Dog
    • Properties: Color, Height, Weight, ...
    • Functionalities: move(), jump(), bark(), ...

Identity: Each object is uniquely identified by an identity, which can be considered as the name of the object.

State: Every object has properties that define its state. The state of an object can only be modified by invoking its behaviors.

Behavior: Behaviors refer to the functionalities (methods) associated with the object. Only behaviors can alter the state of the object.

In object-oriented programming, classes act as blueprints for creating objects. Objects are instances of classes, containing specific data and functionality defined in the class. The class provides a template, and the objects are the concrete instances created based on that template.

Syntax for Creating an Object:

class ClassName:
    def __init__(self, arg1, arg2, ...):
        # Initialize instance variables here

    def method1(self, arg1, arg2, ...):
        # Define method behavior here

# Create an object
obj_name = ClassName(arg1_value, arg2_value, ...)

Example: Creating a Simple Car Object

Let's create a simple Car class and instantiate an object to represent a car. We'll set some properties (attributes) for the car and implement a method (behavior) to display its information.

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

    def display_info(self):
        return f"Car: {self.make} {self.model} ({self.year})"

# Create a Car object
car1 = Car("Toyota", "Corolla", 2022)

# Display Car information using the method
print(car1.display_info())

Output:

Car: Toyota Corolla (2022)

In this example, we defined a Car class with an __init__ method to initialize the instance variables (makemodel, and year). We also created a display_info method to showcase the car's details. We then created a car1 object using the class constructor and passed the necessary arguments. Finally, we printed the information about the car using the display_info method, which displayed the output as Car: Toyota Corolla (2022).

What is a Reference Variable:

In Python, a reference variable is a variable that refers to an object in memory. Instead of directly storing the object itself, the reference variable holds the memory address where the object is located. It acts like a pointer or a link to the object.

Example with Output and Explanation:

Let's consider an example to understand reference variables:

# Define a simple class called Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create two Person objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# Assign person1 to person3
person3 = person1

# Modify the age of person1
person1.age = 26

# Display information of all persons
print("Person 1:", person1.name, person1.age)  # Output: Person 1: Alice 26
print("Person 2:", person2.name, person2.age)  # Output: Person 2: Bob 30
print("Person 3:", person3.name, person3.age)  # Output: Person 3: Alice 26

Explanation:

In this example, we define a simple Person class with an __init__ method to initialize the name and age attributes. We create two Person objects, person1 with the name "Alice" and age 25, and person2 with the name "Bob" and age 30.

Next, we assign person1 to person3 using the = assignment operator. This means that both person1 and person3 now reference the same object in memory. They share the same data.

When we modify the age attribute of person1 to 26, it also affects the age attribute of person3, because both variables point to the same object.

Finally, we display the information of all three persons using the print statements. We can observe that person1 and person3 have the same age, which confirms that they are referencing the same object in memory. person2, on the other hand, is not affected by the changes made to person1, as it references a different object. This behavior exemplifies the concept of reference variables in Python.