Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在赋值之前解决正在解决的变量的异常?_Python_Multithreading_Python 3.x - Fatal编程技术网

Python 如何在赋值之前解决正在解决的变量的异常?

Python 如何在赋值之前解决正在解决的变量的异常?,python,multithreading,python-3.x,Python,Multithreading,Python 3.x,此代码给出了一个错误,编号是分配前的参考: #!/usr/bin/python import threading import time global number number = 1 class myThread(threading.Thread): def __init__(self, threadID): threading.Thread.__init__(self) self.name = threadID def run(sel

此代码给出了一个错误,编号是分配前的参考:

#!/usr/bin/python 
import threading  
import time 
global number
number = 1
class myThread(threading.Thread):
    def __init__(self, threadID):
        threading.Thread.__init__(self)
        self.name = threadID
    def run(self):
        printFunction(self.name)
def printFunction(name):
    while number < 20: 
        number = number +1 
        print number
        print name 
thread1 = myThread(1)
thread2 = myThread(2)
thread1.start()
thread2.start()
#/usr/bin/python
导入线程
导入时间
全局数
数字=1
类myThread(threading.Thread):
def u u init u;(self,threadID):
threading.Thread.\uuuuu init\uuuuuu(自)
self.name=threadID
def运行(自):
printFunction(self.name)
def打印函数(名称):
当数量<20时:
数字=数字+1
打印号码
印刷品名称
thread1=myThread(1)
thread2=myThread(2)
thread1.start()
thread2.start()

如何解决此错误?

这与多线程无关

printFunction
中,您正在访问和操作全局变量
number


您应该将
global number
语句移动到
printFunction
中,因为您正在操作函数中的全局变量。

正如这里提到的另一个答案,问题不在于线程。这意味着您正在修改一个全局变量,而在修改该变量的作用域中没有出现全局限定符。此代码段演示了以下内容:

global_variable = 1

def access():
    # we can access a global variable without using the work "global"
    print("Value of global_variable: {}".format(global_variable))
    return

def qualified_modify():
    # we can modify a global variable if we use the "global" qualifier
    global global_variable 
    global_variable += 1

    return

def unqualified_modify():
    # we can't modify a global variable without the "global" qualifier
    # this function will cause an exception to be raised
    global_variable += 1
    return

access()
qualified_modify()
print("Incremented global variable: {}".format(global_variable))
unqualified_modify()
此代码生成以下输出:

全局_变量的值:1 递增的全局变量:2
回溯(最近一次呼叫最后一次):
文件“global_var.py”,第23行,在
不合格的_modify()
文件“global_var.py”,第17行,在“修改”中
全局变量+=1

请注意,全局限定符需要出现在访问变量的函数中。它告诉解释器在全局范围内查找要修改的变量,但这不是读取全局变量所必需的

由于您没有包括整个堆栈跟踪和异常消息,我不能确定,但我怀疑它指出了
number=number+1
行<代码>而数字<20:应该可以,因为解释器可以找到并读取全局变量,但要修改它,需要告诉解释器该变量是全局变量