Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictonaries and Lambda inside a class?

Tags:

python

lambda

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?

like image 853
UberJumper Avatar asked Jun 14 '26 07:06

UberJumper


1 Answers

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.

like image 107
Cybis Avatar answered Jun 15 '26 23:06

Cybis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!