我正在依赖于布尔变量的 python 类方法上运行循环。当我尝试从外部更改变量的值时,它似乎卡在循环中,我无法更改也无法运行下一行。
import time
class Test:
def __init__(self):
self.counter = 0
self.boolean = True
def test1(self):
while self.boolean:
time.sleep(0.5)
print(self.counter)
self.counter += 1
class Test2:
def __init__(self):
self.test = Test()
self.test.test1()
def stop_test(self):
time.sleep(2)
print("Now I change the boolean value")
self.test.boolean = False
test = Test2()
print("What is going on?")
test.stop_test()
这段代码总结了我的问题。
我期望循环结束,但循环继续运行,代码只打印 self.counter 的值
您可以通过线程实现,例如:
import time
import threading
class Test:
def __init__(self):
self.counter = 0
self.boolean = True
def test1(self):
while self.boolean:
time.sleep(0.5)
print(self.counter)
self.counter += 1
class Test2:
def __init__(self):
self.test = Test()
self.thread = threading.Thread(target=self.test.test1) # Run test1 in a separate thread
self.thread.start() # Start the thread
def stop_test(self):
time.sleep(2)
print("Now I change the boolean value")
self.test.boolean = False
test = Test2()
print("What is going on?")
test.stop_test()