Python Modules

A Module defines a bunch of code which provide special features to its users out of the box.

We’ll be learning how to create a module and access it.

Creating a Module

Specify file extension as .py. Here we’ll be naming our module as NewModule.py.
We’ll assign a method which multiplies the given numbers

fruits = [
    "Orange",
    "Apple",
    "Strawberry"
]

def myfunc(a,b):
    return a*b

To use the method in the module we must include the particular module inside of python file.
Use import followed by module name in our main.py file.

import NewModule

Accessing Method’s inside Module in main.py

import NewModule

k=NewModule.myfunc(9,8)

print(k)

#PYTHON OUTPUT
72

Accessing variables inside module

print(NewModule.fruits)

#PYTHON OUTPUT
['Orange', 'Apple', 'Strawberry']

Renaming module

This is required when the module name is too long insisted calling with that name we can assign an alias to that module

import NewModule as sn

k = sn.myfunc(9, 8)
print(k)
print(sn.fruits)

#PYTHON OUTPUT
72
['Orange', 'Apple', 'Strawberry']

Accessing classes in modules

If you wish to use a particular class/method/variable in module this can be done by from keyword.

#in NewModule.py file

class Teacher:
    def set_teacher(self,name,subject):
        self.name=name
        self.subject=subject

    def show_teacher_details(self):
        return [
            self.name,self.subject
        ]

class Student:
    def set_student(self,fname,lname,age):
        self.fname=fname
        self.lname=lname
        self.age=age

    def show_student_details(self):
        return [
            self.fname,
            self.lname,
            self.age,
        ]


#---------------------------------------
#-----------in main.py file--------------
#---------------------------------------

from NewModule import Student as st #this will only import Student class 

new_st= st()
new_st.set_student("Kane","John",18)
print(new_st.show_student_details())

#PYTHON OUTPUT
['Kane', 'John', 18]

Top Python Posts