【问题标题】:Python: Unable to use variable from another file even though the file is importedPython:即使导入了文件,也无法使用另一个文件中的变量
【发布时间】:2021-02-01 16:40:14
【问题描述】:

我正在尝试编写一个石头、纸、剪刀的游戏,但我收到一个关于我导入的文件没有“quitGame”属性的错误,即使我应该将该变量与其他人。

这是具有quitGame 变量的函数(过滤掉不需要的部分):

def playRps():
    game = "".join([playerAction, computerAction])
    global quitGame

    outcomes = {
        "rr": tied,
        "pp": tied,
        "ss": tied,
        "rp": playerLoss,
        "ps": playerLoss,
        "sr": playerLoss,
        "rs": playerWin,
        "pr": playerWin,
        "sp": playerWin,
    }

    if playerAction == "q":
        quitGame = True  # TODO: Figure out why this isn't working in the main.py file
    else:
        action = outcomes.get(game)
        if action:
            action()
        else:
            print("Invalid input!")

你也可以找到整个functions.py文件here.

这是应该运行程序的main.py 文件(过滤掉不需要的部分):

import functions  # Imports the functions.py file
while True:
    playGame = str(input('Would you like to play "Rock, Paper, Scissors"? (Y/n): '))

    if playGame == "y":
        while True:
            functions.playerChoice()
            functions.computerChoice()
            functions.playRps()
            if functions.quitGame == True:
                break

    elif playGame == "n":
        print("Terminating program...")
        quit()

    else:
        print("Unknown input. Please enter a valid answer.")
        continue

你也可以找到整个main.py文件here.

这是我试图修复的错误的交互:

(.venv) johnny@lj-laptop:rock_paper_scissors$ /home/johnny/Projects/rock_paper_scissors/.venv/bin/python /home/johnny/Projects/rock_paper_scissors/main.py
Would you like to play "Rock, Paper, Scissors"? (Y/n): y

    Rock, paper, or scissors?
    Acceptable responses are...
    "r": Chooses rock.
    "p": Chooses paper.
    "s": Chooses scissors.

    "q": Quits the game.
    r
Tied! No points awarded.
Traceback (most recent call last):
  File "/home/johnny/Projects/rock_paper_scissors/main.py", line 18, in <module>
    if functions.quitGame == True:
AttributeError: module 'functions' has no attribute 'quitGame'

我觉得这很奇怪,因为 playerScorecomputerScore 等其他变量按预期工作。我在每个变量和函数之前添加了functions.,所以它为什么告诉我我没有它是没有意义的。

我什至在创建变量的函数中添加了global quitGame。我不明白为什么这不起作用。

我的问题是:

  • 为什么我在调用该变量时会出错?我做错了什么?

【问题讨论】:

  • 作为一名程序员,您应该非常、非常非常努力不使用全局变量。
  • 也许你可以不用全局并从 playRps() 返回 TrueFalse
  • @LiterallyJohnny 你可以使用一个类。您可以从函数返回变量。您也可以使用 Google 来帮助寻找答案。以下是一些:stackoverflow.com/questions/59330578/…stackoverflow.com/questions/11462314/…
  • @LiterallyJohnny if playRps() == False 确实是正确的语法。这是非常基本的 Python,我建议学习有关如何使用函数的基本教程。
  • 我建议您在接受互联网陌生人的话之前,确保您了解全球员工的好处和陷阱。全局变量确实要付出高昂的代价,但如果你不知道为什么要避开它们,你就不知道什么时候应该避开它们。

标签: python


【解决方案1】:

你必须在变量被“请求”而不是“声明”之前使用 global。

所以如果你想让 quitGame 是全局的,你必须声明它是你喜欢的(例如在 main.py 中)然后你想使用它(作为函数中的示例)使用“global quitGame” .

您可以告诉您的函数访问一个名为quitGame 的全局变量,而不是将quitGame 声明为全局变量。

【讨论】:

  • 哦,有道理。感谢您的回答!
  • 没问题,我也尝试声明 var global 但在 python 中不能这样工作;) p.s.避免全局变量的建议是一个很好的建议
  • 是的,我会记住这一点。我不明白为什么不打算使用全局变量,但我会检查一下,看看为什么。我不介意做研究。
  • 我开发了许多作用于全局变量的函数来修改或读取它们的数据(在小的“单文件”脚本上)。但最佳实践是将您的函数构建为独立于环境,因此全局 var 依赖是一种成本约束。最好的解决方案是开发一个即使在他的环境之外也可以使用的功能。如何?只需将这些变量作为参数传递给函数。
【解决方案2】:

克隆了您的存储库并意识到如果我先选择“q”,然后回答“Y”然后玩游戏,我可以玩游戏。

Would you like to play "Rock, Paper, Scissors"? (Y/n): y

    Rock, paper, or scissors?
    Acceptable responses are...
    "r": Chooses rock.
    "p": Chooses paper.
    "s": Chooses scissors.

    "q": Quits the game.
    q
Would you like to play "Rock, Paper, Scissors"? (Y/n): y

    Rock, paper, or scissors?
    Acceptable responses are...
    "r": Chooses rock.
    "p": Chooses paper.
    "s": Chooses scissors.

    "q": Quits the game.
    r
Tied! No points awarded.
Would you like to play "Rock, Paper, Scissors"? (Y/n): 

这是因为您的 functions.quitGame 全局仅在 functions.playRps() 运行时才被初始化。在此之前,它不存在,因此如果您在选择“y”开始游戏后立即回答“r”,则functions.quitGame 全局还不存在。您可以通过在 computerScore 声明下方的 functions.py 文件中初始化变量来解决此问题:

playerScore = 0
computerScore = 0
quitGame = False

之后,您就可以毫无问题地玩游戏了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2013-01-12
    • 2020-12-18
    • 1970-01-01
    相关资源
    最近更新 更多