在Python中的同一个类中打破其他方法的while循环
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在Python中的同一个类中打破其他方法的while循环,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1911字,纯文字阅读大概需要3分钟。
内容图文
![在Python中的同一个类中打破其他方法的while循环](/upload/InfoBanner/zyjiaocheng/747/4b2d4f87c8c04f3a8639cad0c1c0a0cd.jpg)
我想知道我是否可以在Python类的方法中运行while循环,可以从另一个方法停止.
例如,像这样:
from time import sleep
class example():
global recording
def __init__(self):
pass
def start(self):
global recording
recording = True
while recording:
print(1)
def stop(self):
global recording
recording = False
print("SLEEEPINGGGGGGGGGGG")
a = example()
a.start()
sleep(0.5)
a.stop()
但是,它不起作用,循环不会停止.
编辑
由于我不想在课外创建一个Thread,我只是尝试了这个,但它也不起作用.
from time import sleep
import threading
class example():
def __init__(self):
self.is_running = False
def start(self):
self.is_running = True
self.loop_thread = threading.Thread(target=self.main_loop)
def main_loop(self):
while self.is_running:
sleep(0.5)
print(1)
def stop(self):
self.is_running = False
print("SLEEEPINGGGGGGGGGGG")
a = example()
a.start()
sleep(3)
a.stop()
解决方法:
a.start()是一个无限循环.由于没有任何东西同时运行,它只是运行并且永远不会到达下一个语句.
你需要创建一个这样的线程
import time,threading
class example():
def __init__(self):
self.__recording = False
def start(self):
self.__recording = True
while self.__recording:
time.sleep(1)
print(1)
def stop(self):
self.__recording = False
a = example()
t = threading.Thread(target=a.start)
t.start()
time.sleep(5)
a.stop()
t.join()
请注意,我使用的是成员变量而不是全局变量.当start方法看到变量为True时,它退出循环.任务完成.
这是有效的,因为我正在使用sleep().如果您正在运行纯python CPU密集型作业,由于python GIL将无法工作
正如评论中所建议的那样,您可以更进一步,继承自threading.Thread方法:
import time,threading
class example(threading.Thread):
def __init__(self):
threading.Thread.__init__(self,target=self.run)
self.__recording = False
def run(self):
self.__recording = True
while self.__recording:
time.sleep(1)
print(1)
def join(self):
self.__recording = False
threading.Thread.join(self)
a = example()
a.start()
time.sleep(5)
a.join()
请注意,stop方法现在被join替换,这表示记录线程停止然后调用父连接方法.所以当你加入时,你首先自动停止循环.
内容总结
以上是互联网集市为您收集整理的在Python中的同一个类中打破其他方法的while循环全部内容,希望文章能够帮你解决在Python中的同一个类中打破其他方法的while循环所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。