【问题标题】:The global variable from a function() within a different .py file isnt being found within Python script?在 Python 脚本中找不到来自不同 .py 文件中的 function() 的全局变量?
【发布时间】:2022-01-24 18:41:52
【问题描述】:

当我使用 func.py 文件中的以下函数时,找不到“myName”变量。但是,如果我直接在 wordguess.py 中使用代码(而不是使用它的函数版本),则会找到变量并且它可以工作。

def enter_name():
  global myName
    # Ask the a player for their username
  print("What is your username:")
  myName = input()[0:6]
  print("\n")
  while len(myName)==0:
    print("Please enter your username (Max 6 characters in length):")
    myName = input()
  print("Hi, " + str(myName) + ", welcome to the Word Guessing Game!")
  print("\n")

然后我在主脚本中调用func.enter_name()。我正在使用import func 来包含 func.py 文件。但是我收到以下错误:

  File "wordguess.py", line 116, in main
    outputWriter.writerow({'Name' : myName, 'Date' : dtFullDate, 'Attempts' : attempts, 'Word Chosen' : wordChosen})
NameError: name 'myName' is not defined

如果我将 enter_name() 中的代码直接粘贴到主脚本中,它似乎可以工作(我查看了Using global variables in a function,但无法找出问题所在)。这是引发错误的代码:

with open('scoreboard.csv', 'a', newline='') as outputFile:
        outputWriter = csv.DictWriter(outputFile, ['Name', 'Date', 'Attempts', 'Word Chosen'])
        outputWriter.writerow({'Name' : myName, 'Date' : dtFullDate, 'Attempts' : attempts, 'Word Chosen' : wordChosen})
        outputFile.close()

不确定 csv 模块是否与问题有关。

【问题讨论】:

  • func导入变量时需要使用func.myName
  • 函数返回值比设置全局变量更好。
  • “全局”变量可能应该称为“模块全局”。所以func.enter_name()会影响全局命名空间定义func.enter_name的地方,它在func中,所以检查func.myName
  • 我试过outputWriter.writerow({'Name' : func.myName, 'Date' : dtFullDate, 'Attempts' : attempts, 'Word Chosen' : wordChosen}) 但是它说AttributeError: module 'func' has no attribute 'myName' 你能举个例子吗?非常感谢
  • 它有效@barmer。感谢您的帮助

标签: python python-3.x function variables


【解决方案1】:

根据 cmets 的建议:

  • 我把函数调用写成 func.enter_name()
  • 在 enter_name() 函数中设置“全局 myName”
  • 导入变量时使用了“func.myName”

【讨论】:

    猜你喜欢
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多