To import a module from a package created in Python, follow these steps.
1. Package Structure:
Assume the package structure is as follows:
2.
my_module.py content:3.
__init__.py in my_package (optional but good practice):This file can be empty, or it can be used to control what gets imported when
my_package is imported. For a simple case, an empty __init__.py is sufficient.4.
main.py to import and use the module:Explanation:
from my_package import my_module: This statement imports themy_modulemodule directly from themy_packagepackage.- Once imported, you can access functions, classes, or variables defined within
my_module.pyusing themy_module.prefix (e.g.,my_module.greet("User")).
Alternative Import Syntax:
You can also import specific functions or classes directly:
This approach allows you to use the
greet function without explicitly referencing my_module each time. Choose the import style that best suits the readability and organization of your code.
కామెంట్లు లేవు:
కామెంట్ను పోస్ట్ చేయండి