In Jython, can I create an inline anonymous class that implements the Java interface?

In Java, I can say

Thread t = new Thread(){
    public void run(){ // do stuff }
}

(or something like that) to declare an anonymous inline class. This is most useful for creating event handlers or other types of callbacks that in any reasonable language would not require the object to own them in the first place.

I am facing the same problem in Jython - I want to define an event handler, but I do not want to create a separate stand-alone class for this.

Ideally, I can just pass on the lambda and end it, but if possible, I cannot find it anywhere in the documents.

+5
source share
1 answer

Here are the source links from my original answer:

: Python - Java?

: Python ?

, : Python?

[ ]

Jython , . , :

def _(self, event):
    print 'Cancel button was clicked!'
    if self.task is not None:
        self.task.cancel()
cancelButton.setOnAction(lambda event: _(self, event))

.

(1) . , .

(2) self aware, , self .

(3) () . Python , . , , _, . ( .) ad-infinitum.

, , , :

@LocalEventHandler(self, cancelButton.setOnAction)
def _(self, event):
    print 'Cancel button was clicked!'
    if self.task is not None:
        self.task.cancel()

:

class LocalEventHandler(object):
    '''This decorator turns a local function into a *self aware* event handler.'''

    def __init__(self, context, assignHandlerFunc):
        self.context = context
        self.assignHandlerFunc = assignHandlerFunc

    def __call__(self, handler):
        self.assignHandlerFunc(lambda event: handler(self.context, event))
        return handler
+7

All Articles