views:

466

answers:

2

I have a couple of Jython modules living in the same directory. One of them defines the following class:

from java.lang import Runnable
class MyTask(Runnable):
    def __init__(self, params):
        Runnable.__init__(self)
        self._params = params

    def run(self):
        # do stuff
        print "Done doing stuff"

I can instantiate and run this class just fine from within its own module. However, when I import that module into a different Jython module and try to instantiate MyTask(), I get the following error:

Runnable.__init__(self) AttributeError: class Runnable has no attribute '__init__'

What am I doing wrong here? Why is this code valid within the module where my class is defined, but not when I import that class into another module? (I'm importing it with "import modulename" rather than with "from modulename import MyTask")

Edit: To those who have suggested that the problem is that Runnable is an interface and therefore has no constructor: I know this, but it doesn't fully explain this situation. The crux of the question is that I can instantiate this class within the module where it is defined, but I cannot import it into another module and instantiate it there. i.e.,

In mytask_module:

# this works
if __name__ == '__main__':
    task = MyTask() # works!
    thread = Thread(task) 
    thread.start()

In other_module:

# this throws AttributeError
if __name__ == '__main__':
    import mytask_module
    task = mytask_module.MyTask() # raises AttributeError
    thread = Thread(task) 
    thread.start()

Now do you see the confusion? If the problem was purely as you were describing, then the former example should also raise an AttributeError, but it does not. It runs just fine.

Edit #2: Apparently this does work in a standalone script, but not in my Eclipse/Pydev environment. So the real question is why doesn't Pydev let me do this. If this does work for anyone in their own Pydev/Eclipse environment, please let me know.

A: 

Runnable is an interface... so it has no constructor. I am guessing the call to __init__ is to call the constructor.

TofuBeer
Well, like I said, I can call that code from within the module, so that can't be it. Not sure what Jython does to make that code valid, but I've seen it used elsewhere as well.
Jeff
+1  A: 

The __init__ is the constructor of the jython(python) class

there is yet no 'inferface' in jython. the 'implements' is emulated by inheritance.

if the base class is an interface in java, no constructor exist (no __init__) and you get a :

AttributeError: class Runnable has no attribute '__init__'
Blauohr