Python Module Import and Usage: A Practical Guide
-
Create a Python Module:
- In the folder containing your project, open Notepad (or your preferred text editor) and create a new file.
- Name the file with a descriptive name and add the '.py' extension (e.g., 'my_module.py').
- Add the following code to your module file:
# Variables to import later length, width = 5, 10 # Functions to import later def printInfo(name, age): print('{} is {} years old.'.format(name, age))
-
Import and Use the Module in Jupyter Notebook:
- Open a new Jupyter Notebook.
- In the first cell, import your created module using the following code, replacing '
' with your module's filename:
import <mod>
- In the second cell, print the values of
length
andwidth
from your module:
print(mod.length, mod.width)
- In the third cell, call the
printInfo
function from your module with your name and age as arguments:
mod.printInfo('Your Name', Your Age)
- Run each cell in your Jupyter Notebook to see the results. You should see the values of
length
andwidth
printed, followed by a message displaying your name and age.
-
Important Note:
- Restart the kernel: It's essential to restart the Jupyter Notebook kernel after modifying your module. This ensures that the changes in your module are recognized.
- Don't use %run: Avoid using the
%run
command to execute your module directly within the Jupyter Notebook. Instead, always use theimport
statement for proper module management. - Modify your code: When using a module, always refer to variables and functions within the module using the module name as a prefix (e.g.,
mod.length
,mod.printInfo
).
This process demonstrates the basic steps for creating, importing, and utilizing your own Python modules. This practice enhances code organization, reusability, and maintainability for larger Python projects.

原文地址: http://www.cveoy.top/t/topic/lfrE 著作权归作者所有。请勿转载和采集!