【问题标题】:'Return' function doesn't return variable python“返回”函数不返回变量python
【发布时间】:2020-04-29 16:08:11
【问题描述】:

本质上,变量“存在”不会返回。输出是“假,真,假”,但我不明白为什么会这样。从代码中可以看出,我尝试使变量“存在”global 无效。

我环顾四周,发现了两个类似的问题-Python--Function not returning value、Python: Return possibly not returning value,但不明白为什么我的代码不起作用。

我知道这个问题非常具体——如果我错过了一个愚蠢的错误,那么我会删除它,如果是 Python 警告,那么我会看看我是否可以改写它。

import time
global exists
exists= False

def in_thread(exists):

    print(exists)
    time.sleep(2)
    exists= True
    print(exists)
    return(exists)

in_thread(exists)
print(exists)

【问题讨论】:

  • 如果你修改了一个全局变量的值,你需要在你的函数的开头调用它。这可能是问题的一部分

标签: python-3.x


【解决方案1】:

in_thread 内部的exists 与外部的exists 是不同的变量。如果要使用相同的变量,请使用global 关键字:

exists = False

def somefunction():
    global exists
    exists = True

print(exists)
someFunction()
print(exists)
# False
# True

另外,in_thread 似乎没有返回任何内容,因为您没有将结果分配给任何内容(您只是在打印 exists 的本地版本)。

【讨论】:

    【解决方案2】:

    你真的应该考虑重写你的函数:

    import time
    
    def in_thread():
        exists = False
        print(exists)
        time.sleep(2)
        exists = True
        return(exists)
    
    
    print(in_thread())
    

    它正在返回,但是当您在函数外部声明存在时,它会返回自己的存在版本。而是考虑在函数内部创建它并在 print 语句中调用它,以便打印返回的输出。

    这将导致输出:

    False
    True
    

    如果你想使用你原来写的函数,你需要将你的调用更改为打印语句,以便打印返回值:

    import time
    global exists
    exists= False
    
    def in_thread(exists):
    
        print(exists)
        time.sleep(2)
        exists= True
        print(exists)
        return(exists)
    
    print(in_thread(exists))
    

    【讨论】:

      【解决方案3】:

      print(exists) 返回设置为 False 的全局变量值。

      要从您的函数中打印值,您需要在 print() print(in-thread(exists)) 中调用该函数

      替换: in_thread(存在) 打印(存在)

      有: 打印(in_thread(存在))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多