Python线程在for循环中传递线程对象时出现问题

Python线程在for循环中传递线程对象时出现问题,python,multithreading,Python,Multithreading,为什么这段代码没有给出“服务器”列表中的所有列表变量?我认为它应该打印所有这些主机,而不是只打印列表中的最后一个变量 #!/usr/bin/python import time import threading from threading import Thread import os,sys class InitThread(Thread): def __init__(self,threadID, host): self.host = host se

为什么这段代码没有给出“服务器”列表中的所有列表变量?我认为它应该打印所有这些主机,而不是只打印列表中的最后一个变量

#!/usr/bin/python
import time
import threading
from threading import Thread
import os,sys
class InitThread(Thread):
    def  __init__(self,threadID, host):
        self.host = host
        self.threadID = threadID
        super(InitThread, self).__init__()

    def run(self):
        print host




servers=[ 'yahoo.com','google.com','10.0.0.10','10.0.0.0.11','10.0.0.12']

jobs = []
threadID = 1
for host in servers:
    t=InitThread(threadID,host)
    jobs.append(t)
    threadID += 1
for t in jobs:
    t.start()
    t.join()    
执行上述脚本后,我将获得如下输出:

# python foo.py 
10.0.0.12
10.0.0.12
10.0.0.12
10.0.0.12
10.0.0.12

您正在
run
方法中打印类变量
host
,而不是实例变量
host
。由于该变量在
InitThread
的所有实例中共享,并且最后一个赋值使其成为列表的最后一个元素,因此您将始终打印列表的最后一个元素

您可以通过预加
self
来修复它

#!/usr/bin/python
import time
import threading
from threading import Thread
import os,sys
class InitThread(Thread):
    def  __init__(self,threadID, host):
        super(InitThread, self).__init__()
        self.host = host
        self.threadID = threadID

    def run(self):
        print self.host