简体   繁体   English

在Python中动态实例化类

[英]dynamically instantiate classes in Python

I want to dynamically add threading.Thread classes to a thread queue based on a database query. 我想基于数据库查询动态地将threading.Thread添加到线程queue Is that possible? 那可能吗?

For example: 例如:

import threading, Queue

class worker(threading.Thread):
    def run(self):
        while True:
            print 'doing stuff'

# get jobs from db
jobs = list(db.Jobs.find())

q = Queue.Queue(5)
for job in jobs:
    # instantiate a worker thread here.. don't know how to do this
    ...
    # start new worker thread
    new_worker_thread.start()
    # then add the worker to the queue
    q.put(new_worker_thread)

Any advice would be awesome. 任何建议都会很棒。

Simply use: 只需使用:

new_worker_thread = worker()

This instantiates a new worker thread. 这实例化了一个新的工作线程。 After this you can start and put it in the queue. 在此之后,您可以启动并将其放入队列中。

Some more information on threads can be found here: http://www.tutorialspoint.com/python/python_multithreading.htm 有关线程的更多信息,请访问: http//www.tutorialspoint.com/python/python_multithreading.htm

Very useful tutorial! 非常有用的教程!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM