2

I'm new with python and I can't find why the "Without_thread" class works and not the "With_thread" class.

The purpose of my "With_thread" class is to launch a new thread when I call it with a function so I can execute any function at the same time. (<==This is what I would like to do)

import threading

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

    def run(self):
        self._target(*self._args)

The "Without_thread" is almost the same class, the only thing changing here is that I don't use threads.

class Without_thread():
    def __init__(self, target, *args):
        self._target = target
        self._args = args

    def foo(self):
        self._target(*self._args)

I test my code with this:

def some_Func(data, key):
    print("some_Func was called : data=%s; key=%s" % (str(data), str(key)))

f1 = With_thread(some_Func, [1,2], 6)
f1.start()
f1.join() 

f2 = Without_thread(some_Func, [1,2], 6)
f2.foo()

The output from f1 is:

    self._target(*self._args)
TypeError: 'NoneType' object is not callable

The output from f2 is:

some_Func was called : data=[1, 2]; key=6

I would really appreciate if you can help me with this, and thank you very much for your time!!!

1 Answer 1

2

I suspect the issue is caused by some sort of conflict between your _target and _args and the same attributes defined within Thread.

You don't need to define __init__() or run() in With_thread. The Thread classes own init allows you to pass keyword arguments target and args, and its run() method will run target with args and kwargs provided at intiialisation.

So, you can get rid of With_thread entirely, and then call:

f1 = threading.Thread(target=some_Func, args=([1,2], 6))
Sign up to request clarification or add additional context in comments.

5 Comments

I tried changing the name of the args passed to the thread and the exception jumps. To narrowing the issue, if I print the type of _target is 'NoneType' and it should be <class 'function'>
Ok, we can come back to that. Does my suggestion work? If so, why do you want to subclass Thread?
your solutions works fine. I'm only asking for the reason of why don't works as Rotsap wrote it.
Good question, it works fine for me on python 2.7/x64
in some_Func what values should be their

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.