Larger projects often consist of multiple modules with different functions, such as some handling calculations, some plotting, and some managing GUIs. Multiple modules collaborate to complete complex tasks. To use functions or classes from other modules in a module, the module must first be imported.
Using Built-in Modules and Third-Party Modules
【Excel VBA】
In Excel VBA, third-party modules can be referenced to extend functionality. Refer to Section 10.2 for details.
【Python】
To use functions and classes from built-in modules, the import command must first be used to import the module. The syntax is as follows:
class="text-secondary">import module1[, module2[, ... moduleN]]
When calling a function from a module, use the following format:
module_name.function_name
If only a specific function from the module is needed, use the from…import statement.
Below, the math module is imported in a module, and its sin function, cos function, and constant pi are used to calculate the sine and cosine of 30°. The sample file path is Samples\ch11\Python\sam11-01.py.
class="text-secondary">import math # Import math module
class="text-secondary">from math class="text-secondary">import cos # Import cos function class="text-secondary">from math module
angle = math.pi / 6 # Calculate 30° using constant pi
a = math.sin(angle) # Calculate sine of 30° using math.sin()
b = cos(angle) # Calculate cosine of 30° using cos function
print(a) # Output sine value
print(b) # Output cosine value
In the Python IDLE script file window, select Run → Run Module. The IDLE command-line window displays the following results:
>>> = RESTART: ...\Samples\ch11\Python\sam11-01.py
0.49999999999999994
0.8660254037844387
Using Other Custom Modules
【Excel VBA】
In Excel VBA, procedures and functions in one module can call variables, procedures, and functions defined with the Public keyword in other modules.
In Module 1 in Figure 11-1, if the Private keyword before the Sum function is changed to Public, it becomes a public function and can be called in other modules. Add Module 2 and enter the following code:
Sub Test()
Debug.Print Sum(2, 8)
End Sub
Running the procedure outputs 10 in the Immediate Window.
【Python】
For custom modules, since the storage location of module files is uncertain, directly using the import statement may cause errors. Generally, after importing a module with the import statement, Python searches for the specified module file in the following order:
Current directory (the directory where the module file is located).
Directories specified by the PYTHONPATH (environment variable).
Python’s default installation directory (the directory where the Python executable is located).
Thus, as long as the custom module file is placed in one of these three directories, Python can find it. The most commonly used is the first directory, i.e., placing the imported and importing modules in the same directory.