I have a question regarding the use of global variable. I have a situation something like this: I have to loop through forest and then through hives to find the bee and then the bee should deposit honey in honey_jar.
I could use this approach:
class HoneyJar:
def deposit_honey(self, bee):
print(f"Honey desposited by {bee}")
def loop_bees(nest):
bees = [1, 2, 3, 4] # Assume i have bees from some nest
for bee in bees:
honey_jar = HoneyJar()
honey_jar.deposit_honey(bee)
def loop_hives(forest):
bee_nests = [1, 2, 3, 4] # Assume i have bee_nest from some forest
for bee_nest in bee_nests:
loop_bees(bee_nest)
def main():
forests = ['Amazon', 'Madagascar']
for forest in forests:
loop_hives(forest)
main()
But that would mean I create instance of HoneyJar in every loop.
I could tackle this problem by creating the honey_jar on top level and using it as a global variable.
honey_jar = HoneyJar()
def loop_bees(nest):
global honey_jar
bees = [1, 2, 3, 4] # Assume I have bees from some nest
for bee in bees:
honey_jar.deposit_honey(bee)
What would a better approach?