Python3的简单线程

2024-09-30 14:17:10 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python2中,我使用这个简单的方法运行Thread通过参数传递参数:

import threading


class FuncThread(threading.Thread):
    '''
        it worked fine in Python2
    '''
    def __init__(self, target, *args):
        self._target = target
        self._args = args
        print( self._args )
        threading.Thread.__init__(self)
    def run(self, *args):
      print( self._args )
      self._target(*self._args)

def testThreading(say=''):
  print("I'm a thread %s" % say)

t = FuncThread(testThreading, 'hi')
t.start()

现在在Python3里这已经不起作用了,我开始

^{pr2}$

因为在run重写中,self._args为空。如果我在Python3中使用新语法,它就是

# this works fine in Python3
threading.Thread(target=testThreading, args=('Hello Thread!',)).start()

这很好,那么如何正确地重写run方法?在


Tags: 方法runinselftargetdefargsthread
3条回答

尝试如下:

import threading


class FuncThread(threading.Thread):

    def __init__(self, target, *args):
      threading.Thread.__init__(self)
      self._target = target
      self._args = args
      print( self._args )

    def run(self, *args):
      print( self._args )
      self._target(*self._args)

def testThreading(say=''):
  print("I'm a thread %s" % say)

t = FuncThread(testThreading, 'hi')
t.start()

我以前也遇到过这种情况,在对子类进行任何尝试之前初始化父类,在本例中,FuncThread最终被重写。在

threading.Thread类使用self._target和{}来达到自己的目的。因为您调用的super __init__没有参数,所以在父构造函数中将这些参数设置为None。要解决此问题,只需删除您的__init__在创建实例时使用关键字参数,并让默认行为为您完成任务:

import threading

class FuncThread(threading.Thread):
    def run(self, *args):
      print( self._args )
      self._target(*self._args)

def testThreading(say=''):
  print("I'm a thread %s" % say)

t = FuncThread(target=testThreading, args=('hi',))
t.start()

如果要保留原始构造函数签名,请使用target和{}参数调用父__init__,在这种情况下,您不需要自己显式地设置它们:

^{pr2}$

这是Python3的解决方案:

class FuncThread(threading.Thread):
    def __init__(self, target, *args):
        self._xtarget = target
        self._args = args
        print( self._args )
        threading.Thread.__init__(self)
    def run(self, *args):
      print( self._args )
      self._xtarget(*self._args)

相关问题 更多 >

    热门问题