为什么super(Thread,self).__ init __()对于threading.Thread子类不起作用? [英] Why doesn't super(Thread, self).__init__() work for a threading.Thread subclass?

查看:397
本文介绍了为什么super(Thread,self).__ init __()对于threading.Thread子类不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中认识的每个对象都可以通过调用以下方法来处理其基类的初始化:

Every object I know of in Python can take care of its base class initialization by calling:

super(BaseClass, self).__init__()

threading.Thread的子类似乎不是这种情况,因为如果在SubClass.__init__()中尝试此操作,则会得到:

This doesn't seem to be the case with a subclass of threading.Thread, since if I try this in SubClass.__init__(), I get:

RuntimeError: thread.__init__() not called

是什么导致此错误?我看了threading.Thread的源,看起来__init__方法应该设置Thread.__initialized = True.我看到所有示例都使用以下__init__:

What gives this error? I looked at the source for threading.Thread and it looks like that __init__ method should set Thread.__initialized = True. I see that all examples use the following __init__:

class YourThread(threading.Thread):
    def __init__(self, *args):
        threading.Thread.__init__(self)
        # whatev else

但是为什么?

推荐答案

这很好:

>>> class MyThread(threading.Thread):
...   def __init__(self):
...     super(MyThread, self).__init__()

我认为您代码的错误在于,您正在将 base 类而不是 current 类传递给super,即您正在调用super(threading.Thread, ...,那是错误的.很难说,因为您没有显示失败的代码,但这就是我从您所使用的语言中得出的结论!-)

I think your code's bug is that you're passing the base class, rather than the current class, to super -- i.e. you're calling super(threading.Thread, ..., and that's just wrong. Hard to say since you don't show your failing code, but that's what I infer obliquely from the language you're using!-)

这篇关于为什么super(Thread,self).__ init __()对于threading.Thread子类不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆