5.4 Making Our Own Module
115
functions defined in that module get ready for use. To see that the function y now is
ready for use, we may proceed our interactive session as:
In [2]: ball_function.y(v0=5, t=0.6)
# remember to prefix y
Out[2]: 1.2342
Thus, apart from the undesirable printouts, the import seems to work!
To realize how inappropriate those printouts are, we might consider the following
situation. A friend of yours wants to use your function y. You provide the file
ball_function.py, your friend imports ball_function, and gets two numbers
printed on the screen. Your friend did not ask for those numbers, and would probably
end up reading your code to see what they were all about. It should not be like that.
Our main observation here, is that those undesirable printouts came from
statements placed outside of functions. Thus, the lesson learned, is seemingly that
when preparing modules for import, there should be no statements outside functions.
Or, could there be a way to treat such statements, so that undesirable printouts are
avoided? We will see.
These thoughts will be in the back of our minds as we now proceed to design the
vertical motion module.
Multiple Imports of the Same Module
Note that, when executing a program (or during an interactive session), Python
does keep track of which modules that already have been imported. Thus, if
another import is tried for a certain module, Python avoids the time consuming
and unnecessary task of executing the module file once again (all module
functionality is already in place, ready for use). You can check this out
if you like, by doing a second import ball_function. This time, there
are no printouts! Doing the import differently (i.e., with our example, as
from ball_function import y or from ball_function import *),
would not make any difference.
5.4.2 A Module for Vertical Motion
One simple way to avoid undesirable printouts during import, is to let the module
file contain only function definitions. This is how we will arrange the first version
of our vertical motion module.
We proceed to make ourselves a preliminary version 9 of our new module
file vertical_motion.py. In this file, we place three function definitions only
(which should suffice for our demonstration). One of these, is the y function from
9 Note that only the final version, presented in Sect. 5.4.3, is found on the book’s website.
Précédent

- 136/350

Suivant