python - 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'
我觉得这很奇怪,因为其他变量(例如playerScore
和computerScore
)按预期工作。我已经functions.
在每个变量和函数之前添加了,所以它为什么告诉我我没有它是没有意义的。
我什global quitGame
至在创建变量的函数中添加了。我不明白为什么这不起作用。
我对你们的问题是:
- 为什么调用该变量时会出现错误?我究竟做错了什么?
解决方案
在“请求”而不是“声明”变量之前,您必须使用全局。
因此,如果您希望 quitGame 是全局的,您必须声明它是您喜欢的(例如在 main.py 中),然后您想使用它(如函数中的示例)使用“global quitGame”。
你可以告诉你的函数去访问一个叫做quitGame的全局变量,而不是把quitGame声明为全局变量。
推荐阅读
- javascript - 从数组中获取对象标签并设置为 aria-label
- string - 使用while循环替换Powershell多个字符串
- javascript - Discord.js Music Bot:如何创建一个命令将整个歌曲播放列表添加到队列中
- javascript - 在 React Naive EXPO 中打印图像(屏幕截图)
- css - MaterialUI/CSS 创建这个盒子
- python - 如何检查值是否为无
- processing - 如何在处理中使用 mousePressed() 处理 2 个不同的事件?
- r - 我收到一个错误“火车”和“班级”的长度不同
- sql - SQL - 在雪花中一次查找多个表的记录计数
- java - 如何使用 JPA 分页将数据从 32k 行 Excel 持久化到 MySql 数据库?