Modules and Class Related Tips
Learn how to import a module and implement wrapper functions in a class.
Treat code as a module
Developing modules in Python is straightforward. Technically, any Python file is a module. If you think you’ve never written a module, just check if you’ve written any Python files. We can import them and use the variables, functions, and classes in other programs. As an example, here’s a file, physics.py
, that we may have written to define some useful constants and functions:
# Physics.py
FREE_FALL_ACCELERATION = 9.81
SPEED_OF_LIGHT = 3e8
def emc2(mass):
return mass * SPEED_OF_LIGHT * SPEED_OF_LIGHT
And here’s another file, main.py
, that reuses it:
import physics
mass = float(input("Enter a planet's mass: "))
# User enters 5.9722e24
print(f"The planet's energy is {physics.emc2(mass)} J")
Let’s run the code below.
Get hands-on with 1200+ tech skills courses.