2

In javascript, if I have an object that contains a method that wants to send a signal to outside the object, I might do something like this ...

function class1(arg1){
    ...
    //something has happened - send out an alert
    this.method1();
    ...
}

var obj1 = new class1();

//define function to respond to the request from obj1 
obj1.method1 = function(){ ... }

Is there an equivalent way of doing this in python? (python 2).

spiderplant0
  • 3,872
  • 12
  • 52
  • 91

1 Answers1

2

You can do this in python.

class class1(object):
    def __init__(self, arg):
        self.arg = arg
    def myevent(self):
        self.method1(self)
    def realmethod(self):
        print('arg', self.arg)

def eventhandler(obj):
    print('event')
    obj.realmethod()


>>> obj1 = class1('real object attr')
>>> obj1.method1 = eventhandler
>>> obj1.myevent()
event
('arg', 'real object attr')

As in javascript you want to make sure you set method1 to be callable before it will be called.

Edit: updated code example to make sure you can pass self to eventhandler and use it just like in real method.

zaquest
  • 2,030
  • 17
  • 25
  • thanks very much, by the way, what so you call this kind of pattern? – spiderplant0 Sep 10 '13 at 20:39
  • @Marcin, you're right, but you always can pass `self` from `myevent` to `method1` if you need it there. – zaquest Sep 10 '13 at 20:44
  • @Marcin, I dont want to create a method on the object. I.e. I dont want self to be passed. I just want to alert code outside the object that something has happened - obj1 does not deal with event it is up to code outside obj1 – spiderplant0 Sep 10 '13 at 20:51
  • @Marcin, I did what you said. It works as I expected. Could you be more specific? – zaquest Sep 10 '13 at 20:53
  • Maybe there is a more standard way of doing what i want then – spiderplant0 Sep 10 '13 at 20:55
  • @spiderplant0, I think what you are looking for is called Observer design pattern. However, this is a bad way to implement it. – zaquest Sep 10 '13 at 21:01