Lesson 8
Making Objects the Main Star!
Chapter 4: Python modules
Creating your own module
Let us try creating our own module!
Let’s say we will need a monster
module, which we will use to write a software for kids to play with lots of monsters.
Copy the following code, and save it as libmonster.py
. Note that I have named FACTOR
in uppercase to indicate that it is a constant (a standard and recommended convention in Python)
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
) 👾👾
A note that you should think of libmonster.spawn_monsters()
as calling the spawn_monsters()
function defined in the module libmonster
, rather than a method for a libmonster
object. libmonster
acts more as a namespace to disambiguate where spawn_monsters()
come from, rather than a class instance.