Newbie - bound/unbound method call

Peter Hansen peter at engcorp.com
Tue May 21 08:09:57 EDT 2002


Inyeol Lee wrote:
> 
> 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?

Looks fairly Pythonic to me, but I'm ill-qualified to say...

Better way?  It depends what you are trying to do. :-)  Can you
describe it in English instead of code?  You don't really need
to store the table ahead of time in this case, since you could
always just use apply() and get_attr() to call the methods
directly after building a string representing their names.

> 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'?

The second self is required, I believe, since you are _not_ using
"bound methods".  When you create the table you do not have a specific
instance, so the references are just references to the methods in
that class.  To call them you must give the self argument explicitly.

Alternatively, you could construct the table each time in the 
constructor and store "self.do_key1" and so forth.  Then they
are bound methods and your do() implementation could skip the 
self part.

-Peter



More information about the Python-list mailing list