Custom modules
You can also write your own module, and import your module from another script.
Copy the script below and save it as my_module.py
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
FACTOR = 5
class Monster:
def __init__(self, name="Me", food="cookies"):
self.name = name
self.food = food
def talk(self):
print(f"{self.name} love {self.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 try running this script, nothing will happen (obviously).
Now, let’s write another script to import our module. Call it my_script.py
and save it in the same directory as my_module.py
.
1
2
3
4
5
6
7
8
9
10
11
12
13
import my_module
print(my_module.FACTOR)
print(my_module.calculate_growthrate(2))
monsters = my_module.spawn_monsters()
new_monster = my_module.Monster("Crazy", "sashimi")
monsters.append(new_monster)
for monster in monsters:
monster.talk()
Run your script (python3 my_script.py
), and it should work!