What is a module in Python?

A module is a collection of functions, classes, and variables that we can use from a program. There is a large collection of modules available with the standard Python distribution.

The import statement followed by the name of the module gives us access to the objects defined in it. An imported object becomes accessible from the program or module that imports it, through the identifier of the module, point operator, and the identifier of the object in question.

A module can be defined as a file that contains Python definitions and declarations. The name of the file is the name of the module with the .py suffix attached. We can begin by defining a simple module that will exist in a .py file within the same directory as our main.py script that we are going to write:

  • main.py
  • my_module.py

Within this my_module.py file, we’ll define a simple test() function that will print “This is my first module”:

 # my_module.py
def test():
print("This is my first module")

Within our main.py file, we can then import this file as a module and use our newly-defined test() method, like so:

# main.py
import my_module

def main():
my_module.test()

if __name__ == '__main__':
main()

That is all we need to define a very simple python module within our Python programs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.171.125