Modules and Class Related Tips
Explore how to develop Python modules as reusable code units, manage class attributes for shared data, implement singleton patterns to control instantiation, and customize object string outputs for clearer debugging and presentation.
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.
FREE_FALL_ACCELERATION = 9.81
SPEED_OF_LIGHT = 3e8
def emc2(mass):
return mass * SPEED_OF_LIGHT * SPEED_OF_LIGHTA useful module is not merely a collection of statements, it needs documentation as well.
It needs a testing facility like the one described below. It also needs a purpose and a concept.
Let modules act independently
A module is a unit of pre-packaged, reusable code. A module typically consists of variable, function, and class definitions and is expected to be imported by another program. There’s nothing wrong with having a fully self-contained module that may be executed as a program, rather than as a part of something else, however. Consider a variation of the module, this.
...