0

I am trying to run a simple threading function within my simple class.

I am trying to call the Thread function within a method of a class. This Thread function within this method points to another method within the class. The way I tested it out is through the python terminal. Here is my class in increment_thread.py:

from threading import Thread
import time

class Increment:
    def __init__(self):
        self.count = 0

    def add_one(self):
        while True:
            self.count = self.count + 1
            time.sleep(5)

    def start(self):
        background_thread = Thread(target=add_one)
        background_thread.start()
        print("Started counting up")
        return

    def get_count(self):
        return print(self.count)

In order to test this, I run python in my terminal, which prompt the python terminal.

Then, I run the following lines:

from increment_thread import Increment
inc = Increment()
inc.get_count() # Yields 0
inc.start()

I expect the thread to start and indicate "Started counting up", but instead I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "~/python-sandbox/increment_thread.py", line 14, in start
    background_thread = Thread(target=add_one)
NameError: name 'add_one' is not defined

Is what I am trying to do possible?

1
  • you forgot self. Commented Jul 19, 2019 at 22:41

2 Answers 2

3

In the Thread constructor should it not be target=self.add_one rather than target=add_one

To pass parameters:

from threading import Thread
import time

class Increment:

    count = None

    def __init__(self):
        self.count = 0

    def add_one(self, start_at=0):
      self.count = start_at
      while True:    
        self.count = self.count + 1
        time.sleep(5)

    def start_inc(self, start_at=count):
        # Pass args parameter as a tuple
        background_thread = Thread(target=self.add_one, args=(start_at,))
        background_thread.start()
        print("Started counting up")
        return

    def get_count(self):
        return print(self.count)

if __name__ == "__main__":

  inc = Increment()
  inc.get_count() # Yields 0
  inc.start_inc(start_at=5)
  while True:
    inc.get_count()
    time.sleep(2)
Sign up to request clarification or add additional context in comments.

1 Comment

What if I wanted to send parameters to the add_one method?
2

Just like class fields, class methods need to be referred to using self.method syntax. So

    def start(self):
        background_thread = Thread(target=self.add_one)
        background_thread.start()
        print("Started counting up")
        return

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.