
PYTHON — Accessing Module Objects in Python
Computers are good at following instructions, but not at reading your mind. — Donald Knuth
Accessing Module Objects in Python
In Python, you can access variables, functions, and classes from within the same module by simply using their names. This means that you can directly access these objects without any additional qualifications. Let’s take a look at an example to understand this concept better.
Suppose we have a module named adder.py with the following content:
# adder.py
def add(a, b):
return a + bNow, in another module main.py, we can access the add function from adder.py as follows:
# main.py
import adder
value = adder.add(2, 2)
print(value)By importing the module adder, we can directly access the add function using dot notation (adder.add) and then use it within main.py. This is because both add and main are in the same module, and therefore, they share the same namespace.
To demonstrate this, let’s run the code:
python main.pyThis will output 4, which is the result of adding 2 and 2 using the add function from the adder module.
In summary, accessing objects from inside a module in Python is as simple as using their names within the same module, thanks to the shared namespace.
By understanding how to access module objects, you can effectively organize and utilize your code across different modules within a Python project.
