tags:

views:

123

answers:

1

How can i do something like this:

class Foo():
 do_stuff = { 
   "A" : lambda x: self.do_A(x),
   "B" : lambda x: self.do_B(x)
  }
def __init__(self):
 print "hi"

def run(self):
 muh = ['A', 'B', 'A']
 for each in muh:
  self.do_stuff[each](each)

def do_A(self, moo):
 print "A"

def do_B(self, boo):
 print "B"

if(__name__ == '__main__'):
aFoo = Foo()
aFoo.run()

This results in it giving an error that self isn't defined at the lambda function, but if i remove it. It says do_A or do_B isn't defined.

EDIT

I managed to figure it out. I need to change the lambda expression into something like this:

lambda x, y: x.do_A(y)

and i would call it like:

self.do_stuff[each](self, each)

Is this a terrible idea?

+7  A: 

do_stuff is not an instance variable in your example. It's more like a static variable. You need to define do_stuff within a method (e.g., the init method) where you have a reference to self in order to make it an instance variable. I hope this example clarifies things for you:

class Foo:

  def __init__(self):
    self.do_stuff = { "A": self.do_A, "B": self.do_B }

  def run(self):
    for x in ["A", "B"]:
      self.do_stuff[x]("hi")

  def do_A(self, x):
    pass

  def do_B(self, x):
    pass

Note that the lambda functions aren't necessary. You can just store references to the functions themselves in your dictionary. The notation "self.do_A" will automatically pass self as the first argument.

EDIT: Does anyone know how to make underscores show properly in non-code-sample text?
EDIT: WTH? The preview is showing underscores differently than the post.

Cybis
+1: Simpler. No Lambdas.
S.Lott
To get underscores working, use \ to escape them eg \_\_init\_\_
Brian