Understanding Code Reuse and Modularity in Python 3


Introduction to Object-Oriented Programming(OOP)?

OOP refers to Object-Oriented Paradigm and is referred to as the heart of programming methodology. It includes several concepts like polymorphism, encapsulation, data hiding, data abstraction, inheritance & modularity.

OOP gives data the prime consideration and by providing an interface through the functions associated with it. An object is a self-sufficient entity i.e. it has all the variables and associated functions with it. Objects have characteristics(variables) and features(methods), known as attributes.

What is Modularity?

Modularity refers to the act of partitioning the code into modules building them first followed by linking and finally combining them to form a complete project. Modularity ensures re-usability and thrives to minimize the duplication.

A module in Python is nothing but a file containing Python definitions followed by methods & statements. The module name is generated out of the file name by removing the suffix “.py”. For example, if the file name is prime.py, the module name is prime. Let's create a module. We save the following code in the file prime.py

Example

def isPrimenot(n) :
   # Corner cases
   if (n <= 1) :
      print(“False”)
   if (n <= 3) :
      print(“True”)
   if (n % 2 == 0 or n % 3 == 0) :
      print(“False”)
   i = 5
   while(i * i <= n) :
      if (n % i == 0 or n % (i + 2) == 0) :
         print(“False”)
   i = i + 6
      print(“True”)

When we run the command line we observe;

Command Line

>>> import prime
>>> prime.isPrimenot(3)
True
>>> prime.isPrimenot(8)
False

We can also assign a local name to the module as well and implement the function as described below.

Command Line

>>> import prime
>>> p=prime.isPrimenot
>>> p(8)
False

We can import multiple modules simultaneously and observe their implementation on command line simultaneously.

Command Line

>>> import prime
>>> import math
>>> p=prime.isPrimenot
>>> p(math.log(2,math.pow(2,8))
False

In this way, the code can be used at multiple places without the need of writing it again and again in the code. Hence Modularity supports code reusability and minimal dependencies.

Tip: Each module can be imported exactly once in a single interpreter session. If we change the module’s content or want to reload it, we must restart the interpreter again.

This reloading can also be done manually by running the statement −

>>> reload(modulename)

Conclusion

In this article, we learnt about the reusability of code & the concept of modularity in Python 3.x. Or earlier.

Updated on: 29-Aug-2019

450 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements