【发布时间】:2013-12-23 02:08:32
【问题描述】:
在 python 中使用线程时,我无法理解创建子类的原因。我读过很多网站,包括tutorialspoint。
文档说您需要定义 Thread 类的新子类。我对类有基本的了解,但根本没有玩过子类。我还没有对我使用过的任何其他模块(如 os 和 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.
【问题讨论】:
-
注意:如果您想添加更多信息,您需要编辑自己的帖子,而不是其他人的。对答案的编辑通常会被拒绝(除非你写了答案)。
-
很抱歉。我是这个论坛的新手,还在学习中。
-
你做得很好 - 坚持下去 :-) 听起来你找到的教程只涵盖了一种使用
Thread的方法。但是,正如您已经知道的那样,正如 Python 文档所说,有两种方法。选择你最舒服的方式!没有急于学习一切;-) -
谢谢!我想我也查看了您引用的页面,但是文档中唯一引用 threading.Thread 的部分都提到了将它作为一个类使用。是的,有很多东西要学。我想我无法只见树木不见森林 :)
标签: python subclass python-multithreading