【问题标题】:How to update a global variable如何更新全局变量
【发布时间】:2022-09-22 21:31:38
【问题描述】:

我已经将这些全局变量从我的主模块引入到我的其他模块中,但它们不会更新。我知道这一点,因为我试图在它们应该被更新后打印变量的值。

所有变量都从\'0\'开始

这是\'module_doors\'

def one(pills, batteries, lighter):
  while True:
    doorone = input(\"A, B or C?:\\n\").lower()
    if doorone.lower() not in (\'a\', \'b\', \'c\'):
      print(\"That item doesn\'t exist, try again.\")
      print(\'\')
    else:
      break
  if doorone.lower() == \'a\':
    batteries = 1
    print(\'These could come in handy later.\')

  if doorone.lower() == \'b\':
    lighter = 1
    print(\"Maybe it\'s a light source. Doesn\'t look brand new though, not sure how long it\'ll last.\")

  if doorone.lower() == \'c\':
    pills = 1
    print(\'Could save your life, good choice.\')

然后我尝试将它们打印在另一个模块中进行检查,如下所示:

import module_doors

def lobby(pills, batteries, lighter):
  if lobbydeci.lower() == \'b\':
    print(\"\")
    time.sleep(0.3)
    print(\'Only one key remaining, Nice!\')
    print(\'\')
    print(\"It says \'0001\' on the tag.\")
    module_spacing.spacing()
    module_doors.one(pills, batteries, lighter)
    module_doors.two(pills, batteries, lighter)
    print(batteries)
    print(lighter)
    print(pills)

这只是为所有变量值打印 0,即使它们应该更新。

谢谢

  • 您的代码中没有全局变量。你在说什么全局变量?
  • 他们在我的主模块中:
  • 作为程序员你应该非常努力,非常,非常很难不使用全局变量。
  • 如:电池 = 0,打火机 = 0,药丸 = 0
  • \"他们\'在我的主模块\": 你的主模块在哪里?

标签: python


【解决方案1】:

你应该在最后使用 return ,因为你没有取回变量:

return batteries, lighter, pills

在第二个模型中:

pills, batteries, lighter = module_doors.one(pills, batteries, lighter)

  

【讨论】:

    【解决方案2】:

    如果在函数中修改了这些变量并且您希望保留这些更改,则应该返回这些变量。

    然后将它们重新分配到您调用函数的位置

    像这样的东西:

    def one(pills, batteries, lighter):
        # some stuff
        return pills, batteries, lighter
    
    def lobby(pills, batteries, lighter):
        # some stuff
        return pills, batteries, lighter
    
    pills = 0
    batteries = 0
    lighter = 0
    
    pills, batteries, lighter = one(pills, batteries, lighter)
    pills, batteries, lighter = lobby(pills, batteries, lighter)
    

    从技术上讲,您可以在不传递参数和使用全局变量的情况下执行此操作,但实际上您不应该这样做(请参阅评论中的 Pranav Hosangadi 链接以了解原因)

    PD:药丸电池和打火机似乎是物品。如果您扩展代码以包含更多项目,您应该考虑重构代码并使用列表或字典(您不希望最终将 20 个变量传递给您的函数)

    【讨论】:

      【解决方案3】:

      确保在迭代它们后返回值

      return pills, lighter, batteries
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-20
        • 2013-06-22
        • 2019-06-09
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多