2013-12-23 74 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上实现为实例变量。如果你不需要(还),不要担心(还)。