Dictonaries and lambda inside the classroom?

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 leads to the fact that it gives an error that self is not defined in the lambda function, but if I delete it. He says do_A or do_B are not defined.

EDIT

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

lambda x, y: x.do_A(y)

and I would call it that:

self.do_stuff[each](self, each)

Is this a terrible idea?

+3
source share
1 answer

do_stuff is not an instance variable in your example. This is more like a static variable. You need to define do_stuff in a method (e.g. init method ), where you have a reference to self in order to make it an instance variable. Hope this example clarifies everything 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

, - . . "self.do_A" .

EDIT: - , ?
EDIT: WTH? , .

+7

Source: https://habr.com/ru/post/1699530/


All Articles