0

I have a class thread like this:

import threading, time
class th(threading.Thread):
    def run(self):
        print "Hi"
        time.sleep(5)
        print "Bye"

And now let's say I want every time of "sleeping" different, so I tried:

import treading, time
class th(threading.Thread, n):
    def run(self):
        print "Hi"
        time.sleep(n)
        print "Bye"

It doesn't work, and it give me a message:

group argument must be None for now

So, how do I pass a parameter in the run?

NOTE: I did it with another function in the class like that:

import treading, time
class th(threading.Thread):
    def run(self):
        print "Hi"
        time.sleep(self.n)
        print "Bye"
    def get_param(self, n):
        self.n = n

var = th()
var.get_param(10)
var.start()

2 Answers 2

3

Try this - you want to add the timeout value to the object, so you need the object to have that variable as part of it. You can do that by adding an __init__ function that gets executed when you create the class.

import threading, time
class th(threading.Thread):
    def __init__(self, n):
        self.n = n
    def run(self):
        print "Hi"
        time.sleep(self.n)
        print "Bye"

See more details here.

Sign up to request clarification or add additional context in comments.

2 Comments

selfn should be self.n.
Thank you. I didn't think about it, it was very helpful.
1
class Th(threading.Thread):
    def __init__(self, n):
        super(Th, self).__init__()
        self.n = n
    def run(self):
        print 'Hi'
        time.sleep(self.n)

Th(4).run()

Define a constructor, and pass the parameter to the constructor. The parentheses on the class line delimit the list of parent classes; n is a parameter, not a parent.

Comments

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.