Python Modules का Working
Python के पास Definitions को एक File में रखने और उन्हें Script या Interpreter के Interactive Instance में उपयोग करने का तरीका है। ऐसी File को Module कहते हैं; एक Module से Definitions को अन्य Modules या Main Module (Variables का Collection जो आपको Top Level पर Execute किए गए Script में और Calculator Mode में Access होता है) में Import किया जा सकता है।
जब आप कोई Module Import करते हैं, मान लीजिए hello, तो Interpreter Input Script वाली Directory में hello.py नाम की File Search करता है और फिर PYTHONPATH Environment Variable द्वारा Specified Directories की List में।
Example: Module बनाना और उपयोग करना
fibonacci.py नाम की File बनाएं और इसमें निम्न Code डालें:
def fib(n):
# n तक Fibonacci Series Print करें
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n):
# n तक Fibonacci Series Return करें
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
अब अपना Terminal खोलें और cd Command का उपयोग करके इस File वाली Directory में जाएं और Python Shell खोलें। निम्न Statements Enter करें:
>>> import fibonacci >>> fibonacci.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibonacci.fib2(100) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
आपने Module Import किया और इसके Functions का उपयोग किया।
Module Search Path:
import sys
print('\n'.join(sys.path))
Module Reloading:
import importlib import fibonacci # Code बदलने के बाद importlib.reload(fibonacci)
Module का __name__ Attribute:
# fibonacci.py में
print(__name__) # 'fibonacci' जब Import किया गया
# '__main__' जब Directly Run किया गया
if __name__ == '__main__':
# यह Code केवल तब Run होता है जब Script Directly Execute हो
fib(1000)