Несколько лямбда-функций в сжатом списке не выполняются - PullRequest
0 голосов
/ 13 февраля 2020

Я хочу выполнить несколько функций, которые имеют разные аргументы, когда условие выполнено, но я никогда не выполню ни одну из них:

conditions = [condition1, condition2, condition3]
functions = [lambda: self._f(), lambda x: self._f2(a), lambda x,y: self._f3(b, c)]

for condition, function in zip(conditions, functions):
    if condition:
        function() # execute the proper function with 0, 1 or 2 arguments
        break

def _f():
    print('function1 with no arguments')

def _f2(x):
    print(f'function2 with one argument {x}')

def _f3(x, y):
    print(f'function2 with two arguments {x} and {y}')

Но когда условие выполнено, соответствующая функция не выполняется , Что я делаю не так ??

Заранее спасибо !!

1 Ответ

0 голосов
/ 13 февраля 2020

Надеюсь, это поможет:

Вариант 1:

class MyTestClass:
    def loopTest(self, type, value, value2):
        # necessary to iterate over the values later on
        possibleArgs = [value, value2]

        conditions = [type == 'YES', type == 'MAYBE', type=='TRY AGAIN']
        # here you made the mistake that the first lambda expression didnt call the function "_f" it just "looked" at the reference
        sentences = [lambda: self._f(), lambda x: self._f2(x), lambda x,y: self._f3(x, y)]

        for condition, sentence in zip(conditions, sentences):
            if condition:
                # necessary to pass the arguments to the function
                # "sentence.__code__.co_argcount" gives us the number of arguments of the function
                args = (possibleArgs[i] for i in range(sentence.__code__.co_argcount))
                sentence(*args)
                break

    def _f(self):
        print('executed')

    def _f2(self, x):
        print(f'executed with value {x}')

    def _f3(self, x, y):
        print(f'executed with values {x} and {y}')

MyTestClass().loopTest("TRY AGAIN", 5, 2)
# output: executed with values 5 and 2

Вариант 2:

class MyTestClass:
    def loopTest(self, type, value, value2):
        a = value
        b = value2

        conditions = [type == 'YES', type == 'MAYBE', type=='TRY AGAIN']
        # here you made the mistake that the first lambda expression didnt call the function "_f" it just "looked" at the reference
        sentences = [lambda: self._f(), lambda: self._f2(a), lambda: self._f3(a, b)]

        for condition, sentence in zip(conditions, sentences):
            if condition:
                sentence()
                break

    def _f(self):
        print('executed')

    def _f2(self, x):
        print(f'executed with value {x}')

    def _f3(self, x, y):
        print(f'executed with values {x} and {y}')

MyTestClass().loopTest("TRY AGAIN", 5, 2)
# output: executed with values 5 and 2
...