我想動態地將threading.Thread
類添加到基於數據庫查詢的線程queue
。那可能嗎?在Python中動態實例化類
例如:
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)
任何意見將是真棒。
值得注意的是,[PEP-8](http://www.python.org/dev/peps/pep-0008/)(Python風格指南)建議'CapWords'保留給類,'lowercase_with_underscores '用於變量。你可能想要遵循這個來讓你的代碼更具可讀性。 –
Ahm,new_worker_thread = worker()有什麼不對? –
哦,對,因爲實例化一個同名的worker不會覆蓋現有的對象..我現在認識到 – MFB