Newbie - bound/unbound method call

Inyeol Lee inyeol_lee at yahoo.com
Tue May 21 05:02:04 EDT 2002


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

Thanks for your advice. I'm a newbie in both Python and OOP.
Inyeol



More information about the Python-list mailing list