10 – Modules in Python

Have you ever wondered how modules are created? In this post, we will be creating a module. When your programs become larger it should be split into smaller parts. Which is achieved using import command in python.

Create a program named mbp.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#save it as mbp.py
 
class MYBTECHPROJECTS:
   'Learn what you like'
   #Object Initialization
   total_no_of_posts=26
 
   def __init__(self,name):
      self.name = name
 
 
   def return_no_of_posts(self,lang):
     if lang=="python":
         return 10
     if lang=="NodeMCU":
         return 6

To use variables and functions in mbp.py import it into another program using import mbp

1
2
3
4
5
6
7
8
9
#Tested in Python Shell 
#Can be used in another program also
>>> import mbp
>>> o=mbp.MYBTECHPROJECTS("Gowtham")
>>> o.total_no_of_posts
26
>>> o.return_no_of_posts("python")
10
>>>

 From module_name import *, can be used to access classes or functions of the module without using the module name 

1
2
3
4
5
6
7
8
>>> #using from program import *
>>> from mbp import *
>>> o=MYBTECHPROJECTS("Gowtham")
>>> o.total_no_of_posts
26
>>> o.return_no_of_posts("python")
10
>>>

THANK YOU FOR COMPLETING PYTHON  BASIC COURSE

SHARE THIS!!!

Gowtham S

Gowtham is a programming enthusiast. His field of interest includes Arduino, NodeMCU, Raspberry Pi, and Python. To know more about him visit https://mybtechprojects.tech/about-us/.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.