Python for Java Programmers
Chapter 9: Modules
Custom modules
You can also write your own module, and import your module from another script.
Copy the following code, and save it as libmonster.py.
FACTOR = 5
class Monster:
def __init__(self, name="Me", food="cookies"):
self.name = name
self.food = food
def spawn_monsters():
return [Monster("Happy", "carrots"),
Monster("Bashful", "ice-creams"),
Monster("Wild", "cookies")]
def calculate_growthrate(adjustment=3):
return 25 * FACTOR + adjustment
If you run this script (i.e. python3 libmonster.py), nothing will happen (obviously, since these are all just definitions).
Now, let’s write another script to import and use our yummy libmonster module. Save the following file as game.py, in the same directory as libmonster.py.
import libmonster
print(libmonster.FACTOR)
print(libmonster.calculate_growthrate(2))
monsters = libmonster.spawn_monsters()
new_monster = libmonster.Monster("Crazy", "sashimi")
monsters.append(new_monster)
for monster in monsters:
print(f"{monster.name} love {monster.food}!")
Then run python3 game.py, and it should work!
So, you now have a module called libmonster that you can import from any script (in our case, in game.py) 👾👾