10

I have this class:

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) 

and am calling it with this script:

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

and get this error and I can't figure out why: unbound method __init__() must be called with instance as first argument

Winston Ewert
  • 44,070
  • 10
  • 68
  • 83
Leonidas
  • 2,110
  • 4
  • 20
  • 31

4 Answers4

17

You are doing:

Thread.__init__() 

Use:

Thread.__init__(self) 

Or, rather, use super()

mthurlin
  • 26,247
  • 4
  • 39
  • 46
  • 7
    That'd be `super(Thread, self).__init__()` -- but super has it's own problems too :/ – Jochen Ritzel Oct 23 '09 at 18:35
  • 2
    @THC4k: Super has no problems, multiple inheritance has problems. And if you use multiple inheritance then super is much much better than direct calls. – nikow Oct 24 '09 at 09:03
  • super is just a recipe for disaster, specially so in multiple inheritance, more specially if there is any extensions that need reloading. – dashesy Sep 09 '14 at 21:10
9

This is a frequently asked question at SO, but the answer, in brief, is that the way you call your superclass's constructor is like:

super(Timer,self).__init__()
Jonathan Feinberg
  • 44,698
  • 7
  • 80
  • 103
3

First, the reason you must use:

Thread.__init__(self)

instead of

Thread.__init__()

is because you are using the class name, and not an object (an instance of the class), so you cannot call a method in the same way as an object.

Second, if you are using Python 3, the recommended style for invoking a super class method from a sub class is:

super().method_name(parameters)

Although in Python 3 is possible to use:

SuperClassName.method_name(self, parameters)

It is an old style of syntax that is not the prefer style.

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
1

You just need to pass 'self' as an argument to 'Thread.init'. After that, it works on my machines.

tsellon
  • 2,396
  • 5
  • 24
  • 33