我有一個問題,圍繞在python中使用線程時創建子類的理由。我讀過很多網站,包括tutorialspoint。Python線程 - 創建子類?
該文檔說你需要定義一個新的Thread類的子類。我對課程有一個基本的瞭解,但根本沒有玩過亞類。我沒有必須做任何這樣的事情,但我用任何其他模塊,如操作系統& ftplib。任何人都可以指向一個可以更好地解釋這個新手腳本的站點嗎?
#!/usr/bin/python
import threading
class myThread (threading.Thread):
我可以寫我自己的腳本,而無需創建這個子類和它的作品,所以我不知道爲什麼,這都是一項要求。這是我創建的一個簡單的小腳本,用於幫助我最初理解線程。
#!/usr/bin/python
# Import the necessary modules
import threading
import ftplib
# FTP function - Connects and performs directory listing
class
def ftpconnect(target):
ftp = ftplib.FTP(target)
ftp.login()
print "File list from: %s" % target
files = ftp.dir()
print files
# Main function - Iterates through a lists of FTP sites creating theads
def main():
sites = ["ftp.openbsd.org","ftp.ucsb.edu","ubuntu.osuosl.org"]
for i in sites:
myThread = threading.Thread(target=ftpconnect(i))
myThread.start()
print "The thread's ID is : " + str(myThread.ident)
if (__name__ == "__main__"):
main()
感謝您的幫助!我的參考資料是tutorialspoint.com。這聽起來像你說我咬得比我咀嚼的更多,我現在應該保持簡單,因爲我不需要使用更復雜的選項。這是網站這樣說:
Creating Thread using Threading Module:
To implement a new thread using the threading module, you have to do the following:
- Define a new subclass of the Thread class.
- Override the __init__(self [,args]) method to add additional arguments.
- Then, override the run(self [,args]) method to implement what the thread should do when started.
Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which will in turn call run() method.
注意:如果您想添加更多信息,您需要編輯自己的帖子,而不是其他人。編輯答案通常被拒絕(除非你寫了答案)。 –
對不起。我對這個論壇很陌生,仍然在學習繩索。 – user2565554
你做得很好 - 保持它:-)聽起來像你找到的教程只涵蓋了使用'Thread'的一種方式。但是,正如你已經知道的那樣,正如Python文檔所說,有兩種方法。選擇你最舒服的方式!有沒有急於學習一切;-) –