是什么导致"未绑定的方法__init __()必须使用实例作为第一个参数调用"来自此Python代码?

Leo*_*das 10 python init

我有这门课:

from threading import Thread 
import time

class Timer(Thread): 
    def __init__(self, interval, function, *args, **kwargs): 
        Thread.__init__() 
        self.interval = interval 
        self.function = function 
        self.args = args 
        self.kwargs = kwargs 
        self.start()

    def run(self): 
        time.sleep(self.interval) 
        return self.function(*self.args, **self.kwargs) 
Run Code Online (Sandbox Code Playgroud)

我用这个脚本调用它:

    import timer 
    def hello():
        print \"hello, world
    t = timer.Timer(1.0, hello)
    t.run()
Run Code Online (Sandbox Code Playgroud)

并得到此错误,我无法弄清楚原因: unbound method __init__() must be called with instance as first argument

tru*_*ppo 16

你在做:

Thread.__init__() 
Run Code Online (Sandbox Code Playgroud)

使用:

Thread.__init__(self) 
Run Code Online (Sandbox Code Playgroud)

或者说,使用 super()

  • 那是'超级(线程,自我).__ init __()` - 但是super也有它自己的问题:/ (7认同)
  • @ THC4k:Super没有问题,多重继承有问题.如果你使用多重继承,那么super比直接调用要好得多. (2认同)

Jon*_*erg 9

这是SO的常见问题,但简而言之,答案就是你调用超类的构造函数的方式如下:

super(Timer,self).__init__()
Run Code Online (Sandbox Code Playgroud)