function और classes के collection को ही module कहते हैं। या simply हम कह सकते हैं modules code library होते हैं। कोई भी file जिसमे में कई सारे functions या classes हैं उसे module कह सकते हैं।

Python Create Module

module create करने के लिए simply किसी file need के according code लिखे फिर उस file को .py extension से file save कर दे। File को दिया गया name ही module कहलाता है।

Python Module Example

सबसे एक new file open करें , इसे mymodule.py से save कर दें। फिर इसके अंदर एक simple function define कर दें।

File : mymodule.py

Copy Fullscreen Close Fullscreen
def welcome(name) :
	print('Welcome : ', name)

बस आपका mymodule name से एक module ready हो गया।


Use Module

module को use करने के लिए सबसे पहले उसे import करना पड़ता है , module import करने के लिए import keyword का use किये जाता है।

File : mymodule.py

Copy Fullscreen Close Fullscreen
import mymodule
# now we can access everything using module name.
mymodule.welcome('Rahul Kumar.')
Output
C:\Users\Rahulkumar\Desktop\python>python module_ex.py
Welcome :  Rahul Kumar.

कुछ इस तरह से module को use करते हैं। दरअसल module को import करने का मतलब है उस file को include करना जिसका code हम use करना चाहते हैं।

Use variables And Class

हालाँकि ये जरूरी नहीं है कि module में सिर्फ functions ही हों , आप अपनी need के according classes और variables भी रख सकते हैं।
For Example -

File : mymodule.py

Copy Fullscreen Close Fullscreen
# define class.
class A :
	def welcome(self) :
		print('Class A function from module.')

# define variable.
mylist = ['Mohit', 'Girish', 'Aryan', 'Gyansingh']

File : module_ex.py

Copy Fullscreen Close Fullscreen
import mymodule
#use class.
obj = mymodule.A()
obj.welcome()

# use variable.
print(mymodule.mylist)
Output
C:\Users\Rahulkumar\Desktop\python>python module_ex.py
Class A function from module.
['Mohit', 'Girish', 'Aryan', 'Gyansingh']

Python Alias Module Name

as keyword का use करके आप module name का name change करके दूसरा name रख सकते हैं।
See Example -

import mymodule as mm
#use class.
obj = mm.A()
obj.welcome()

# use variable.
print(mm.mylist)

Access A Particular Variable / Function / Class

जब हम import module लिखते हैं तो उस module का complete code accessible होता है , अगर आप module में define एक particular variable / function / class access करना चाहते हैं तो उसके लिए from keyword का use किया जाता है।
Example -

from mymodule import A
#now we have only class A from the module.
obj = A()
obj.welcome()

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers