Reputation: 4470
I just entered into python programming (i have experience with java). I want to implement callback/listener in a class. I confused with available samples. I just implemented a sample. Please guide me
my python class as follows
class myClass:
def __init__(self):
self.__result = 0
def connect(self):
self.__result = 1
my main python code as follows
import myClass
def on_connect(result):
print("Connected with result code "+result)
myclass = myClass()
myclass.on_connect = on_connect
myclass.connect()
I just wanted to receive result in on_connect method main code. How to modify the myClass for this ?
Thanks in advance
Upvotes: 1
Views: 9357
Reputation: 1971
Create a class that accept the callback as argument:
class MyClass:
def __init__(self, on_connect=None):
self._result = 0
# store callback reference in a variable
self._on_connect = on_connect
def connect(self):
self._result = 1
# if callback is defined and it is a function/method
if self._on_connect and callable(self._on_connect):
# Send the object instance to the callback,
# you may use the same callback for multiple objects.
self._on_connect(self)
def get_result(self):
return self._result
Then:
import MyClass
def on_connect_callback(instance):
print('Connected with result code {}'.format(
instance.get_result()))
my_obj = MyClass(on_connect=on_connect_callback)
my_obj.connect()
Upvotes: 2
Reputation: 5458
Let's add handlers to the class, with nice add
method and general fire
that calls the callbacks:
class myClass:
def __init__(self):
self.__result = 0
self.on_connect = []
def connect(self):
self.__result = 1
self.fire()
def add_listener(self, listener):
self.on_connect.append(listener)
def fire(self):
for listener in self.on_connect:
listener(self.__result)
Then we only need to redo one thing in your main code - the way we add the listener.
import myClass
def on_connect(result):
print("Connected with result code "+result)
myclass = myClass()
myclass.add_listener(on_connect)
myclass.connect()
Upvotes: 2