【问题标题】:Global variables in multiples functions in PythonPython中多个函数中的全局变量
【发布时间】:2015-09-25 21:27:09
【问题描述】:

我会尝试用例子来解释我的情况:

我使用全局来声明一个变量,但这仅适用于一个函数,当我尝试另一个子函数时不起作用。

注册.py

def main():
    alprint = input("Enter something: ")
    if alprint == "a":
        def alCheck():
            global CheckDot
            CheckDot = input("Enter your opinion: ")
        def alTest():
            global CheckTest
            CheckTest = input("Hope it works: ")
        alCheck()
        alTest()
main()

和 content.py

from register import CheckTest

if CheckTest == "ad":
    print("You are welcome!")

当我在 main 的子函数(function, alTest()) 中声明这个变量 checkTest,使用全局并导入另一个文件时,它不起作用,我尝试了很多东西,但没有。

【问题讨论】:

  • 我认为除了全局变量之外,您还有其他问题(无论如何,它们通常是个坏主意)。将这两个函数定义移出 if 子句。代替全局变量,使用return
  • 感谢您的回复,能给我一个简单的想法或例子吗?
  • 嗯,我会,但目前还不清楚您首先要构建什么。

标签: python function variables import global


【解决方案1】:

工作,除了如果用户在第一个input 中输入了a 以外的其他内容,CheckTest 没有定义,所以它给出了一个ImportError。您可能想尝试这样的事情:

def main():
    global CheckTest, CheckDot
    def alCheck():
        global CheckDot
        CheckDot = input("Enter your opinion: ")
    def alTest():
        global CheckTest
        CheckTest = input("Hope it works: ")
    alprint = input("Enter something: ")
    if alprint == "a":
        alCheck()
        alTest()
    else:
        CheckTest = None
        CheckDot = None
main()

这样,CheckTestCheckDot 始终被定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2015-09-26
    相关资源
    最近更新 更多