Python:lamda与if / else

时间:2018-08-03 10:51:19

标签: python

我试图用if / else代替lambda self.status: partial if max_refundable == amount else self.status = refunded以使其成一行。但是,它不能按预期工作。有人知道问题出在哪里吗?

if max_refundable == amount:
    self.status = partial
else:
    self.status = refunded

2 个答案:

答案 0 :(得分:5)

因为语法无效

lambda self.status: partial if max_refundable == amount else self.status = refunded

等价于

def _lambda_func_(self.status):
    return partial if max_refundable == amount else self.status = refunded

这不是您想要的(self.status不是有效的参数名称)。您不需要功能,只需

self.status = partial if max_refundable == amount else refunded

答案 1 :(得分:0)

语法如下:

a = 1
b = 3
a = a+b if a == 2 else b

在您的情况下,它看起来像这样:

self.status = partial if max_refundable == amount else refunded