[Tutor] Dict of function calls

Pete pkoek11 at xs4all.nl
Wed Sep 22 22:07:21 CEST 2010


For a plugin mechanism, I'm populating a dict with calls to the implemented plugins. 

Consider this:

>>> class foo:
...     def do(self):
...             print 'do foo'
... 
>>> class bar:
...     def do(self):
...             print 'do bar'
... 
>>> list = { 'foo': foo.do(), 'bar': bar.do() }
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method do() must be called with foo instance as first argument (got nothing instead)

===

Now I get that I need to instantiate foo and bar first before I can refer to them in the dict.

so something like

foo_instance = foo()
bar_instance = bar()

list = { 'foo': foo_instance.do(), 'bar': bar_instance.do() }

would probably work. But is that the best/pythonic way to do it? 
I first implemented "do" as a static method but that seemed... wrong (also because it needs to access some variables from the instance).

Any hints would be appreciated,

Pete




More information about the Tutor mailing list