class EventSource(object):
def __init__(self):
self._callbacks = []
def register(self, callback):
print('register:', callback)
self._callbacks.append(callback)
def notify(self, *args, **kwargs):
for callback in self._callbacks:
callback(*args, **kwargs)
class EventHandler(object):
def __init__(self, name):
self.name = name
def foo(self, *args, **kwargs):
print('foo:', self.name, *args, **kwargs)
def bar(self, *args, **kwargs):
print('bar:', self.name, *args, **kwargs)
print('method:', EventHandler.foo, EventHandler.bar)
s = EventSource(); x = EventHandler('x'); y = EventHandler('y')
s.register(x.foo); s.register(y.foo)
s.register(x.bar); s.register(y.bar)
s.notify('first')
s.notify('second')
Item 28: Bound Method
Posted by Logan Chien