Calling a function or method by name

Pedro Rodriguez pedro_rodriguez at club-internet.fr
Wed Jan 23 11:46:25 EST 2002


"Jonathan Gardner" <jgardn at alumni.washington.edu> wrote:

> I don't even know where to look for the answer to this one. If I have a
> function name, stored in a string, how do I call that function? I have a
> feeling it has something to do with apply() and __dict__, but I don't
> know how to start looking.
> 
> In particular, if I have a class with several subclasses, and I want to
> call a method, how is that done?
> 
> What is this for? Well, I want my class to respond to keys being
> pressed. Each key will trigger a call to a class method with no
> arguments (except self). I don't want to have a huge if/elif structure
> because that is slow. I want to use a dict. The keys will be the value
> of the key being pressed. The values will be the name of the function to
> call.
> 
 
You may start with :

class A:
    def trigger(self, key):
        callback = self.callbacks.get(key)
        if callback is not None:
            callback(self, key)
        else:
            self.callDefault(key)

    def callBack1(self, key):
        print "1", key

    def callBack2(self, key):
        print "2", key

    def callDefault(self, key):
        print "Default", key

    callbacks = {
        "a" : callback1
        , "b" : callback2
        , "c" : callback2
        }

a = A()
a.trigger('a')
a.trigger('b')
a.trigger('c')
a.trigger('d')


Regards,
-- 

Pedro





More information about the Python-list mailing list