114
5 Some More Python Essentials
moves without any air resistance. 7 As with built-in modules, we will see that functionality may be imported in the usual ways, e.g., as import vertical_motion,
which allows easy reuse of module functions.
5.4.1 A Naive Import
Before turning to the making of our vertical motion module, we will do some
“warm-up” testing with a previous script of ours, just to enlighten ourselves a bit.
Let us pick ball_function.py from Sect. 4.1.1 (which addresses vertical
motion), and argue that, if this script is a module, we should be able to “import
it” as import ball_function, right? This sounds like a reasonable expectation,
so without too deep reasoning, let us just start there.
First, however, we better take another look at that code (after all, it has been a
while). For easy reference, we just repeat the few code lines of ball_function.py
here:
def y(v0, t):
g = 9.81
# Acceleration of gravity
return v0*t - 0.5*g*t**2
v0 = 5
# Initial velocity
time = 0.6
# Just pick one point in time
print(y(v0, time))
time = 0.9
# Pick another point in time
print(y(v0, time))
We recognize the function definition of y and the two applications of that
function, involving a function call and a printout for each of the chosen points in
time.
Now, we previously thought of this code as a program, executed it, and got the
printouts. What will happen now, when we rather consider it a module and import it?
Here is what happens:
In [1]: import ball_function
1.2342
0.52695
What? Printing of numbers? We asked for an import, 8 not something that looks like
program execution!
The thing is, that when any module is imported, Python does actually execute the
module code (!), i.e., function definitions are read and statements (outside functions)
executed. This is Python’s way of bringing module content “to life”, so that, e.g.,
7 The reader who is into physics, will know that the computations done here, work equally well if
the object has some simultaneous horizontal motion. In that case, our computations apply to the
vertical component of the motion only, not the motion as a whole.
8 Doing the import differently, e.g., like from vertical_motion import y, would still give the
printouts! Also if the import were done in a script.
Précédent

- 135/350

Suivant