我有一个问题,围绕在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文档所说,有两种方法。选择你最舒服的方式!有没有急于学习一切;-) –