Reputation: 41
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
Reputation: 11
You can do this as follow:
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