首页 > 解决方案 > Python:即使导入了文件,也无法使用另一个文件中的变量

问题描述

我正在尝试编写一个石头、纸、剪刀的游戏,我收到一个关于我导入的文件没有“ 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文件

这是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文件

这是给我我要修复的错误的交互:

(.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至在创建变量的函数中添加了。我不明白为什么这不起作用。

我对你们的问题是:

标签: python

解决方案


在“请求”而不是“声明”变量之前,您必须使用全局。

因此,如果您希望 quitGame 是全局的,您必须声明它是您喜欢的(例如在 main.py 中),然后您想使用它(如函数中的示例)使用“global quitGame”。

你可以告诉你的函数去访问一个叫做quitGame的全局变量,而不是把quitGame声明为全局变量。


推荐阅读