user3234347
user3234347

Reputation: 41

stop a loop in an object method

I have a class with two methods in python 2.7.9 as follow:

class test:

    def __init__(self):
         self.a=True

    def print_hi(self):
         if self.a==True:
              while True:
                   print 'hi'

    def stop(self):
         self.a=False

if __name__=='__main__':
    play=test()
    play.print_hi()
    play.stop()

How I can stop the while loop in 'print_hi', whenever I want, by calling 'stop' method? I know I have to change the code in such a way that in each iteration of the while loop, the value of instance variable 'a' (self.a) can be checked. I want to do so through stop method. Is there a pythonic way to do that?

Upvotes: 0

Views: 40

Answers (1)

dailey
dailey

Reputation: 11

You can do this as follow:

  1. Inherit the threading.Thread
  2. Add a new method(run) for your class, which call the method "self.print_hi()"
  3. When you want to run the method, just call "start".
  4. When you want to stop the loop, call "stop".

PS : You can change "True" to "self.a", I think it's will be better.

import threading
import time

class test(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.a=True

    def run(self):
        self.print_hi()

    def print_hi(self):
        while self.a:
            print 'hi'

    def stop(self):
        self.a=False

if __name__=='__main__':
    play=test()
    play.start()
    time.sleep(2)
    play.stop()

Upvotes: 1

Related Questions