Modules
Modules is a collection of functions and classes in a seperate .py
other than your main.py
file that can be imported and used in your scripts. They are a way to reuse/organize your code.
How to use a module
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py
added. Within a module, the module’s name (as a string) is available as the value of the global variable __name__
.
Consider the following folder structure:
my_project/
│
├── my_script.py
└── my_module.py
This is the content of my_module.py
:
def my_module_function():
print("Hello from my_module_function")
class MyModuleClass:
def __init__(self):
print("Hello from MyModuleClass")
This is the content of my_script.py
:
import my_module
def my_script_function():
print("Hello from my_script_function")
my_class = my_module.MyModuleClass()
my_script_function()
my_module.my_module_function()
In this example, my_script.py
is a script that uses the module my_module.py
. The module my_module.py
is a file that contains the definitions and statements that are used in my_script.py
.
Different ways to import a module
There are different ways to import a module:
import my_module # Import the entire module
my_class = my_module.MyModuleClass()
my_module.my_module_function()
import my_module as mm # Import the entire module and give it a name
from my_module import MyModuleClass # Import a specific object not all
my_class = MyModuleClass()
from my_module import * # Import all objects from the module
my_class = MyModuleClass()
my_module_function()
🛠 Exercise
Module for exercise 1 and 2: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 01: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍