2013-12-23 78 views
1

我有一個問題,圍繞在python中使用線程時創建子類的理由。我讀過很多網站,包括tutorialspointPython線程 - 創建子類?

該文檔說你需要定義一個新的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. 
+0

注意:如果您想添加更多信息,您需要編輯自己的帖子,而不是其他人。編輯答案通常被拒絕(除非你寫了答案)。 –

+0

對不起。我對這個論壇很陌生,仍然在學習繩索。 – user2565554

+0

你做得很好 - 保持它:-)聽起來像你找到的教程只涵蓋了使用'Thread'的一種方式。但是,正如你已經知道的那樣,正如Python文檔所說,有兩種方法。選擇你最舒服的方式!有沒有急於學習一切;-) –

回答

1

文檔說你需要定義Thread類的新的子類。

我可以寫我自己的腳本,而無需創建這個子類和它的作品,所以我不知道爲什麼,這都是一項要求。

的Python文件說沒有這樣的事,並不能猜測哪些文檔你談論。 Here are Python docs

有兩種方法來指定該活動:通過使可調用對象的構造函數,或通過在一個子類覆蓋run()方法。在子類中不應該重寫其他方法(構造函數除外)。換句話說,只能覆蓋此類的init()和run()方法。

您正在使用在那裏指定的第一個方法(將可調用方法傳遞給Thread()構造函數)。沒關係。當可調用對象需要訪問狀態變量時,子類變得更有價值,並且您不希望使用全局變量來混淆程序,特別是在使用多個線程時,每個線程都需要它們自己的狀態變量。然後狀態變量通常可以在您自己的子類threading.Thread上實現爲實例變量。如果你不需要(還),不要擔心(還)。