Python Thread子类__init__未调用问题排查及代码分析
问题根源:构造函数拼写错误!
你这里的问题太典型了——把类的构造函数名字写错了!你写的是__int__,但Python里类的构造函数应该是__init__(两个下划线+init+两个下划线)。
为什么会触发AttributeError?
当你创建MonitoringWorker实例时,Python会自动调用类的__init__方法完成初始化,但你定义的__int__是一个完全无关的方法,Python根本不会主动调用它。这就导致你在__int__里定义的threads_hashtag、queue_hashtag等自定义属性完全没有被初始化,哪怕你在这个方法里调用了父类的构造函数,整个方法都没执行过!
等到run方法执行时,尝试访问self.threads_hashtag这些属性,自然就会抛出AttributeError——因为它们从来没被创建过。
修正后的代码
只需要把__int__改成__init__就解决了:
import threading from queue import Queue # 假设HashtagWorker是你已定义的类 class HashtagWorker: def __init__(self, q1, q2, idx): self.q1 = q1 self.q2 = q2 self.idx = idx class MonitoringWorker(threading.Thread): # 这里把__int__改为__init__! def __init__(self, threads_hashtag: int = 1, threads_image: int = 4, threads_user: int = 1): self.threads_hashtag = threads_hashtag self.threads_image = threads_image self.threads_user = threads_user self.queue_hashtag = Queue() self.queue_image_meta_first = Queue() self.queue_image_meta_second = Queue() self.queue_image_meta_third = Queue() self.queue_user = Queue() super().__init__() def run(self): workers_hashtag = [HashtagWorker(self.queue_hashtag, self.queue_image_meta_first, i) for i in range(self.threads_hashtag)] # 后续逻辑可以正常执行了 print(f"Created {self.threads_hashtag} HashtagWorker instances") if __name__ == '__main__': m = MonitoringWorker() m.start() m.join()
额外小提醒
你现在把super().__init__()放在子类属性初始化之后的写法很合理,这能避免父类构造函数意外覆盖子类属性的情况(虽然在threading.Thread场景下影响不大,但这是个值得保持的编程习惯)。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

