Skip to main content

Modules in Python




What are Modules in Python? 

Modules are simply a ‘program logic’ or a ‘python script’ that can be used for variety of applications or functions. We can declare functions, classes etc in a module.

A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.

Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.




How To Create Modules In Python?

Creating a module in python is similar to writing a simple python script using the .py extension. For the above example lets try to make a module for the various operations.

1
2
3
4
5
6
7
8
9
10
11
def add(x,y):
     return x + y
 
def sub(x, y):
     return x - y
 
def prod(x, y):
    return x * y
 
def div(x, y):
    return x / y

Save the above code in a file Calc.pyThis is how we create a module in python. We have created different functions in this module. We can use these modules in our main file, lets take a look at how we are going to use them in a program.

How To Use Python Modules?

We will use the import keyword to incorporate the module into our program, from keyword is used to get only a few or specific methods or functions from a module. Lets see what are different methods to use a module in your program.

Lets say we have our file with a name main.py.

1
2
3
4
5
6
import calc as a
a = 10
b = 20
 
addition = a.add(a,b)
print(addition)

In the above code, we have created an alias using the as keyword. The output of the above code will be the addition of the two numbers a and b using the logic specified in the add function in the calc.py module.

Lets take a look at another approach.

1
2
3
4
5
from calc import *
a = 20
b = 30
 
print(add(a,b))

In the above code, we have imported all the functions using the asterisk and we can simply mention the function name to get the results. 

Python Module Path

When we import a module, the interpreter looks for the module in the build-in modules directories in sys.path and if not found, it will look for the module in the following order:

  1. Current directory
  2. PYTHONPATH
  3. Default directory
1
2
3
import sys
 
print(sys.path)

To add Your file path to the system path.You can use


m_directory="home/python_files"
sys.path.append(m_directory)
#

When you run the above code, you will get the list of directories. You can make changes in the list to create your own path. 

Comments

Popular posts from this blog

Is-A and Has-A relationships in python

  In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House. #Is-A relationship --> By Inheritance class  A:    def   __init__ ( self ):      self .b= 10    def   mym1 ( self ):      print ( 'Parent method' ) class  B(A):    def   mym2 ( self ):      print ( 'Child method' ) d = B() d.mym1() #output: Parent method d.mym2() #output: Child method HAS-A Relationship:  Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom. Let’s understand...

Magic Methods in Python

  What Are Dunder Methods ? In Python, special methods are a set of predefined methods you can use to enrich your classes.  They are easy to recognize because they start and end with double underscores, for example  __init__  or  __str__ . Dunder methods let you emulate the behavior of built-in types.  For example, to get the length of a string you can call  len('string') . But an empty class definition doesn’t support this behavior out of the box: These “dunders” or “special methods” in Python are also sometimes called “magic methods.” class NoLenSupport : pass >>> obj = NoLenSupport () >>> len ( obj ) TypeError : "object of type 'NoLenSupport' has no len()" To fix this, you can add a  __len__  dunder method to your class: class LenSupport : def __len__ ( self ): return 42 >>> obj = LenSupport () >>> len ( obj ) 42 Object Initialization:  __init__ "__init __ ...

Inheritance and Types in Python

  Inheritance   Creating a new class from existing class is known as inheritance . The class from which features are inherited is known as base class and the class into which features are derived into is called derived class . Syntax: class  derived- class (base  class ):       < class -suite>      Inheritance promotes reusability of code by reusing already existing classes.  Inheritance is used to implement  is-a  relationship between classes.   Following hierarchy is an example representing inheritance between classes:   Single inheritance   When a derived class inherits only from syntax, the base class is called single inheritance. If it has one base class and one derived class it is called single inheritance.   Diagram     Syntax class  A:  #parent class         #some code       class  b(A):...