Modules in Python
Last updated Aug 13, 2021Modules in Python
Python modules can be defined as python files containing functions, classes, and variables (in the form of arrays, directories, objects, etc.) used in an application.
Modules are either building modules or user-defined modules.
Import Statement
For using a module in Python we must have to use an import statement first and with the help of the import statement, we can import any python file, module, or package which is either stored in your pc or is available online. Import is the basic statements that are used in calling a module and a package. We can easily call a module using an import statement followed by the name of the module.
USER-DEFINED MODULES
Create a module: To create a module you have to simply make a python file and code in that file and save it using the.py extension.
Example: Save the below code with name code.py
person1 = { "name": "Raftaar", "age": 10, } |
Call a Module: Python file that you have created early can be called in another python file using an import statement.
import code a = code.person1["age"] print(a) |
10 |
In the above example, the earlier code.py was called in another python file.
BUILD-IN MODULES
There are several builds in modules in python one just have to import whatever they want as a module:
import moduleName moduleName.function()#use that module function |
Variables in Module
Variables, Functions, arrays, objects, etc. can be contained in a module and can be used by another file using the import function.
Example: Save the below code with name code1.py
person1 = { "name": "Gojo", "age": 12, "country": "Japan" } Make another python file and import the code1.py import code1 a = code.person1["name"] print(a) |
Gojo |
Renaming a Module:
Anyone can easily rename a module you just have to create an alias when import a module for doing so you have to use a keyword.
Example:
a = pyhon.person["age"] print(a) |
dir() function
While importing a build-in function sometimes you don’t know what function to be used from that module. Here dir() function helps to list all the functions in that module. Simply import any module and use keyword dir(module name) it will automatically provide the list of all the functions in that module
Example
import platform x = dir(platform) print(x) |
Article Contributed By :
|
|
|
|
158 Views |