【问题标题】:Python Threading - Creation of a subclass?Python 线程 - 创建子类?
【发布时间】: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


【解决方案1】:

文档说您需要定义 Thread 类的新子类。

我能够在不创建这个子类的情况下编写自己的脚本并且它可以工作,所以我不确定为什么将其作为要求。

Python 文档没有说这样的话,并且无法猜测您在谈论哪个文档。 Here are Python docs:

有两种方法可以指定活动:通过将可调用对象传递给构造函数,或通过覆盖子类中的 run() 方法。不应在子类中覆盖任何其他方法(构造函数除外)。也就是说,只覆盖这个类的init()和run()方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-24
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    相关资源
    最近更新 更多