Newbie - bound/unbound method call

Steffen Ries steffen.ries at sympatico.ca
Fri May 24 08:02:24 EDT 2002


inyeol_lee at yahoo.com (Inyeol Lee) writes:

> This code is for handling keywords.
> 
> class C:
> 
>     def do_key1(self):
>         print "key1 done."
> 
>     def do_key2(self):
>         print "key2 done."
> 
>     def do_key3(self):
>         print "key3 done."
> 
>     table = {
>         "key1": do_key1,
>         "key2": do_key2,
>         "key3": do_key3
>     }
> 
>     def do(self, key):
>         self.table[key](self)
> 
> This code works fine, for example:
> 
> >>> c = C()
> >>> c.do("key1")
> key1 done.
> >>>
> 
> But I don't fully understand why it works. I've just made it work
> through trial & error. My question is;
> 
> 1. Is it pythonic? Is there better way to do this?

I would use a variation of this theme, but I wouldn't judge one or the
other to be more pythonic:

class C:
    def do_key1(self):
        print "key1 done."
    def do_key2(self):
        print "key2 done."
    def do_key3(self):
        print "key3 done."

    def do(self, key):
        return getattr(self, "do_" + key)()

This way I'm assuming a naming convention to bind the keyword to its
handler.

> 2. Is the second 'self' in the last line 'self.table[key](self)'
>    required? (It generates TypeError without it.) Is it unbound method call
>    even though it starts with 'self'?

It is unbound, since the first self is just used to lookup the
class-variable "table". "table" contains references to the unbound
methods do_keyX

An alternative would be to initialize your table with bound methods in
a constructor:
     def __init__(self):
         self.table = {
             "key1": self.do_key1,
             "key2": self.do_key2,
             "key3": self.do_key3
             }

/steffen
-- 
steffen.ries at sympatico.ca	<> Gravity is a myth -- the Earth sucks!



More information about the Python-list mailing list