[Tutor] dictionary of methods calling syntax

Gregory, Matthew matt.gregory at oregonstate.edu
Tue Feb 7 20:32:28 CET 2012


Hi list,

I'm trying to understand how to use a class-level dictionary to act as a switch for class methods.  In the contrived example below, I have the statistic name as the key and the class method as the value.

class Statistics(object):
    STAT = {
        'MEAN': get_mean,
        'SUM': get_sum,
    }
    def __init__(self, a, b):
        self.a = a
        self.b = b
    def get_mean(self):
        return (self.a + self.b) / 2.0
    def get_sum(self):
        return (self.a + self.b)
    def get_stat(self, stat):
        f = self.STAT[stat.upper()]
        return f(self)

if __name__ == '__main__':
    spam = Statistics(4, 3)
    print spam.get_stat('mean')
    print spam.get_stat('sum')

When I try to run this, I get:

  NameError: name 'get_mean' is not defined

If I move the STAT dictionary to the bottom of the class, it works fine.  I understand why I get an error, i.e. when the dictionary is created get_mean hasn't yet been defined, but I'm wondering if there is a better common practice for doing this type of lookup.  My web searches didn't come up with anything too applicable.

thanks, matt


More information about the Tutor mailing list