[Baypiggies] bound and unbound methods

Monte Davidoff davidoff56 at alluvialsw.com
Mon Jun 25 03:25:37 CEST 2012


On 6/24/12 2:39 PM, Ian Zimmerman wrote:
>
> So I'm looking for something like this:
>
>        handler_table = (
>            ('ev1', self.handle_ev1),
>            ('ev2', self.handle_ev2),
>            )
>
>        def __init__(self):
>            for e, h in self.handler_table:
>                SRP.register(e, some_python_magic(self, h))

If I am understanding the question correctly, I think some_python_magic 
could be functools.partial.

Here is a small working example of what I understood to be the key parts 
of your program:

====================================
class SRP(object):

     def __init__(self):
         self.handlers = {}

     def register(self, tag, handler):
         self.handlers[tag] = handler

     def __call__(self, n):
         for tag, handler in self.handlers.items():
             print tag, handler(n)

class C1(object):

     def h1(self, n): return n + 1
     def h2(self, n): return n + 2

     def __init__(self, srp):
         self.table = (
             ('e1', self.h1),
             ('e2', self.h2),
         )
         for e, h in self.table:
             srp.register(e, h)

srp = SRP()
C1(srp)
srp(10)
====================================

It seemed to me you were looking for something like this:

====================================
from functools import partial

class C2(object):

     def h1(self, n): return n + 1
     def h2(self, n): return n + 2

     table = (
         ('e1', h1),
         ('e2', h2),
     )

     def __init__(self, srp):
         for e, h in self.table:
             srp.register(e, partial(h, self))

srp = SRP()
C2(srp)
srp(20)
====================================

Monte


More information about the Baypiggies mailing list