
PYTHON — Importing Objects in Python
The great myth of our times is that technology is communication. — Libby Larsen
Calling an Imported Object in Python
When working with Python, you will often need to import objects from one module into another. This allows you to use functions and variables defined in one file in a different file. In this tutorial, you will learn how to call an imported object in Python using clear and concise examples.
Importing Modules
To import an object from a module in Python, you can use the import statement followed by the name of the module. For example, if you have a module named adder.py and you want to import it into another file, you can use the following code:
import adderIt’s important to note that the name you use to import the module should be the same as the module’s filename without the .py extension.
Module Filenames
Module filenames in Python must be valid Python identifiers. This means they can only contain upper and lowercase letters, numbers, and underscores, and they cannot start with a digit. These rules are the same as those for naming Python variables.
Calling an Imported Object
Once you import a module into another, the contents of the imported module become available in the calling module. The calling module is the file into which the module is being imported. For example, if adder.py is the imported module and main.py is the calling module, you can call the imported function in main.py.
Example
Here’s an example of importing a module and calling an object from it:
# adder.py
def add(x, y):
return x + y# main.py
import adder
result = adder.add(3, 5)
print(result) # Output: 8In this example, the add function defined in the adder module is imported into the main module using the import statement. Then, the add function is called in the main module to add 3 and 5, resulting in 8.
By following these simple steps, you can effectively import objects from one module into another and call them as needed.
In conclusion, understanding how to import and call objects from modules in Python is essential for building modular and organized code. This allows you to reuse code, keep your files concise, and improve the maintainability of your projects. With the knowledge gained from this tutorial, you can confidently work with imported objects in Python. Happy coding!
