这段Python代码为什么会出现“unbound method __init__() must be called with instance as first argument”的错误?

10

我有这个类:

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) 

我现在正在调用以下脚本:

    import timer 
    def hello():
        print \"hello, world
    t = timer.Timer(1.0, hello)
    t.run()

我遇到了这个错误,但不知道为什么: 未绑定的方法 __init__() 必须使用实例作为第一个参数调用

4个回答

17

你正在做:

Thread.__init__() 

使用:

Thread.__init__(self) 

或者更好的方法是使用super()


7
那将是super(Thread, self).__init__()——但是超级函数也有它自己的问题:/ - Jochen Ritzel
2
@THC4k:Super没有问题,多重继承有问题。如果你使用多重继承,那么super比直接调用要好得多。 - nikow
super只是灾难的配方,特别是在多重继承中,更特别是如果有任何需要重新加载的扩展。 - dashesy

9
这是一个在SO上经常被问到的问题,但简而言之,调用超类构造函数的方式如下:
super(Timer,self).__init__()

3

首先,使用的原因:

Thread.__init__(self)

替换为
Thread.__init__()

这是因为您使用了类名而不是对象(类的实例),所以您不能像使用对象时那样调用方法。
其次,如果您使用Python 3,则从子类调用超类方法的推荐样式是:
super().method_name(parameters)

虽然在Python 3中可以使用:

SuperClassName.method_name(self, parameters)

这是一种旧的语法风格,不是首选的风格。


1

你只需要将“self”作为参数传递给“Thread.init”即可。之后,在我的机器上它可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接