1

having a class

class MyClass:
    def func_a(self):
        """do a"""

    def func_b(self):
        """do b"""

and a mapping

mapping = {
    "A": lambda: Myclass.do_a,
    "B": lambda: Myclass.do_b
}

I would like to be able to do something like this:

thing = Myclass()

for i in ["A", "B"]:
    # call things appropriate method

So in the case of ["A", "B"] first call func_a on thing, and then func_b. How could I do that?

Thanks!

bayerb
  • 649
  • 2
  • 9
  • 28

2 Answers2

1

You don't need lambda for that

mapping = {
    "A": MyClass.func_a,
    "B": MyClass.func_b
}

thing = MyClass()

for i in ["A", "B"]:
    mapping[i](thing)
Guy
  • 46,488
  • 10
  • 44
  • 88
0

You're on the right track! To achieve what you're looking for, you can use the mapping you provided to dynamically call the methods of your MyClass instance. However, you need to make a couple of adjustments to your mapping and function calls.

Here's how you can do it:

class MyClass:
    def func_a(self):
        print("do a")

    def func_b(self):
        print("do b")

thing = MyClass()

mapping = {
    "A": lambda: thing.func_a(),
    "B": lambda: thing.func_b()
}

for i in ["A", "B"]:
    mapping[i]()  # Call the appropriate method based on the mapping

In this code, the lambda functions defined in the mapping call the corresponding methods on the thing instance of MyClass. The loop iterates over the list ["A", "B"], and for each item, it calls the corresponding lambda function, which in turn calls the appropriate method on the thing instance.

Atzuki
  • 627
  • 1
  • 5
  • 16