Python3中的简单线程

时间:2019-02-28 16:21:09

标签: python python-3.x python-2.7 python-multithreading

在Python2中,我使用了这种简单的方法来通过args运行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中,它不再起作用了,而我得到了

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "main.py", line 11, in run
    self._target(*self._args)
TypeError: 'NoneType' object is not callable

因为在run中覆盖self._args为空。如果我在Python3中使用新语法,则为

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

行之有效,那么如何正确覆盖run方法呢?

3 个答案:

答案 0 :(得分:2)

基本threading.Thread类出于自身目的使用self._targetself._args。因为您正在调用不带参数的超级__init__,所以它们在父构造函数中被设置为None。要解决此问题,只需在创建实例时删除__init__ use关键字args,然后让默认行为为您完成工作即可:

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()

如果您想保留原始的构造函数签名,请使用__init__target参数调用父级args,在这种情况下,您无需自己明确设置它们:

import threading

class FuncThread(threading.Thread):
    def __init__(self, target, *args):
        super().__init__(target=target, args=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()

答案 1 :(得分:1)

尝试如下:

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最终被覆盖。

答案 2 :(得分:1)

这是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)