DEV Community

Cover image for How to code in Python(using paradigms)
EdemGold for This is Learning

Posted on

How to code in Python(using paradigms)

Introduction

Programming Paradigms are the different approaches to solving computational problems through programming.

In this article, we will be talking about programming Paradigms, why they're an important part of programming, the different programming paradigms that can be applied using python, and how to apply them.

Programming Paradigms

Image description

Before we delve into programming paradigms, it is crucial to understand the meaning of Paradigms in its basic form, unrelated to computer science, paradigms are essentially the models, guidelines or patterns by which certain objectives are achieved, analogically, they can be likened to how scaffolding serves as the basic structure for buildings.

Programming Paradigms are the different styles which a program can be written in a certain programming language, they are the different ways in which code in a given programming language (like Python, Java, JavaScript, etc) can be organised.

In simple words, every programming language has a special way (methodologies) in which it's code can be structured and run and these are called programming paradigms, some programming languages only support the use of one paradigm, these are called single paradigm languages while others support multiple paradigms, these are called multi paradigm languages.

There are 2 core classifications of Programming Paradigms, and they are:

  • Imperative: In this technique, the programmer specifies how to solve a particular program in the code, examples of paradigms that follow this technique include; Procedural and Object Oriented Programming.

  • Declarative: In this technique, the programmer only declares the problem to be solved without explicitly describing how it is to be solved, examples of paradigms that follow this technique are; Functional Programming, reactive programming, etc

Python Paradigms

As stated earlier, every programming language has it's paradigm style or styles(depending on it's architecture), for example, perhaps the most popular programming language in the imperative division is C which was designed as a single paradigm language(supporting only Imperative programming styles), on the other hand, Haskell, while being obscure, is a great example of a language which supports Declarative programming.

As stated earlier on, the focus of this article will be python and the paradigms it supports. Python is a multi paradigm language as it support procedural, Functional, and Declarative paradigms.

In this article we will explain Python's two most popular paradigms (Object Oriented Programming and Functional programming) and present their code implementations.

Functional Programming

In simple words, Functional programming is a programming paradigm which emphasizes on writing code in little reusable blocks called functions, rather than the changing of states, it takes in one or more inputs and performs computations on them based on a pre-written set of rules and then returns an output without changing any of the data outside the function. It is declarative by nature.

Here is an example of a simple function and its usage

#defining the function
def add(x, y):
  ans = x+y
  return ans

Enter fullscreen mode Exit fullscreen mode
#using the function
a = 2

b = 3

ans = add(a,b)

print(ans)

Enter fullscreen mode Exit fullscreen mode

Higher order functions

Higher order functions are basically functions which have other functions passed as arguments, for example using our other example;

#defining a higher order function

def answer(func, x, y):
  res = func(x,y)
  print(res)


#using higher order functions
answer(add, a, b)


Enter fullscreen mode Exit fullscreen mode

Object Oriented Programming (OOPs)

Object Oriented Programming, is a programming paradigm which deals with code as objects; giving it properties and behaviours. For example, a house is an object with properties like; color, a door, roof, stairs, etc.

In Object Oriented Programming, objects are defined with their properties and behaviours, now the interactions between the properties and behaviours of these objects is what creates the logic for a computer program.

Analogically, you can think of Object Oriented Programming(OOPs) as Lego bricks, combining the bricks in diffrent ways produces different objects, combining them in a certain way can get you a house, combining them in another way can get you a car, in the same manner, combining properties of objects in a certain way creates a logic in the code which generates a certain output.

Image description

Classes
Classes are a crucial part of Object Oriented Programming, they are essentially a set of functions that define and construct the structure of objects, you can think of them as a blueprint for a building in the sense that they outline how a structure should be built.

Magic Methods
Magic methods(also called Dunder methods), they are essentially used to create customisation for objects in classes, they start and end with underscores.

Code implementation


 # Creating the class
class Pet(object):
    """Class object for a pet."""

    def __init__(self, species, name):
        """Initialise a Pet."""
        self.species = species
        self.name = name

    def __str__(self):
        """Output when printing an instance of a Pet."""
        return f"{self.species} named {self.name}"


# Creating an instance of the class
my_dog = Pet(species="dog",
             name="Breakthrough")
print (my_dog)
print (my_dog.name)

Enter fullscreen mode Exit fullscreen mode

Above we created a class for pets, created the magic methods init & str which help in initialising instances of the class and parsing strings for output, respectively.

Object Functions

Objects can also have functions which provide certain behaviour for the objects.

code implementation


 def change_name(self, new_name):
        """Change the name of your Pet."""
        self.name = new_name

# Using the change_name function
my_dog.change_name(new_name="Chivoma")
print (my_dog)
print (my_dog.name)

Enter fullscreen mode Exit fullscreen mode

Above we created a function which made it possible to change the name of the pet object.

Inheritance

This is another really interesting feature of OOPs. Inheritance makes it possible to inherit the behaviours and properties of a certain class and implement them in another class, this makes it possible to build classes on-top of each other.

code implementation

#creating class
class Dog(Pet):
    def __init__(self, name, breed):
        super().__init__(species="dog", name=name)
        self.breed = breed

    def __str__(self):
        return f"A {self.breed} dog named {self.name}"

#creating an instance of the class
Ariel = Dog(species="dog", breed="Great Dane", name="Ariel")
print (Ariel)

Enter fullscreen mode Exit fullscreen mode

Above we created a class named Dog which inherited from the Pet class.

Summary

In conclusion, Paradigms are crucial in designing the structure, organisation, flow, and logic of computer software and every programming language has paradigms it supports. A language can either support one paradigm (single paradigm) or more than one(multi paradigm).

Two of the most popular paradigms supported by Python are Functional Programming and Object Oriented Programming(OOPs).

Functional Programming deals with writing code in little reusable blocks called functions rather than the changing of states, it takes in one or more inputs performs computation on them based on a pre-written set of rules and then returns an output without changing any of the data outside the function. It is declarative by nature.

On the other hand, Object Oriented Programming deals with code as objects; giving it properties and behaviours. For example, a house is an object with properties like; color, a door, roof, stairs, etc.

Due to its vast application in AI and Data Science/Engineering, Python continues to grow in popularity, as such, it is important for developers to have a solid understanding of these programming paradigms in order to write efficient and maintainable code.

By embracing functional programming and OOP principles, developers can create software that is scalable, modular, and easy to maintain, ensuring that their code is well-structured, optimised, and future-proof.

Oldest comments (0)