[Tutor] dictionary of methods calling syntax

Joel Goldstick joel.goldstick at gmail.com
Tue Feb 7 21:20:34 CET 2012


On Tue, Feb 7, 2012 at 2:32 PM, Gregory, Matthew
<matt.gregory at oregonstate.edu> wrote:
> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

You might want to read through this:
http://stackoverflow.com/questions/5213166/python-forward-declaration-of-functions-inside-classes

Specifically from an answer:
    "First, in class B, the function foo() is called before being
declared. A does not have this problem because foo() is only called
when the class is instantiated--after the function foo is defined."

So, I think you could move your STAT dictionary definition into the
__init__ method so that is doesn't actually run until you create an
instance of your class.  That being said, I'm not sure that is more
'pythonic' than moving it to the bottom of the class definition

-- 
Joel Goldstick


More information about the Tutor mailing list