关于Python线程:创建子类?

Python Threading - Creation of a subclass?

在使用Python中的线程时,围绕创建子类的原因,我的大脑有一个问题。我读过很多网站,包括家教网站。

文档说您需要定义线程类的新子类。我对类有一个基本的理解,但根本没有使用子类。我还没有用过其他模块,比如OS&ftplib,来做类似的事情。有人能给我指出一个可以更好地为新手编剧解释这一点的网站吗?

1
2
3
4
5
#!/usr/bin/python

import threading

class myThread (threading.Thread):

我可以在不创建子类的情况下编写自己的脚本,而且它也可以工作,所以我不确定为什么要将此声明为需求。这是我创建的一个简单的小脚本,帮助我初步理解线程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/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作为参考资料。这听起来像是你说的我咬得太多了,我现在应该保持简单,因为我还不需要使用更复杂的选项。网站上这样说:

1
2
3
4
5
6
7
8
9
10
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.


The docs say you need to define a new subclass of the Thread class.

I was able to write my own script without creating this subclass and it works so I am not sure why this is stated as a requirement.

python文档没有这样的说法,也无法猜测您所说的是哪个文档。下面是python文档:

There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. No other methods (except for the constructor) should be overridden in a subclass. In other words, only override the init() and run() methods of this class.

您正在使用这里指定的第一个方法(将一个可调用传递给Thread()构造函数)。那很好。当可调用的需要访问状态变量,并且您不想为了这个目的用全局变量来混乱您的程序时,特别是当使用多个线程时,每个线程都需要它们自己的状态变量时,子类变得更有价值。然后状态变量通常可以作为实例变量在您自己的threading.Thread子类上实现。如果你还不需要,那就别担心。