我应该使用全局变量还是在此示例中还有其他选项?
我有一个有关使用全局变量的问题。我有这样的情况:我必须循环穿过森林,然后穿过蜂巢才能找到蜜蜂,然后蜜蜂应该将蜂蜜存放在Honey_jar中。
我可以使用这种方法:
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()
但这意味着我在每个循环中都会创建Honeyjar实例。
我可以通过在顶级创建Honey_jar并将其用作全局变量来解决这个问题。
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)
什么会更好?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如马蒂亚斯(Matthias)所建议的那样,您应该在主机中使用类似的东西。
第一件事是在主机中创建一个honeyjar的一个实例,
然后传递对其他方法的引用。
而您的loop_hives和loop_bees将是:
As Matthias suggested you should use something like this in your main.
First thing is to create a single instance of HoneyJar in the main,
then pass the reference to the other methods.
And your loop_hives and loop_bees would be :