Python3.8-海象运算符
场景:假设某位顾客在果汁店点了一杯柠檬水,店员需要确保篮子里至少有一个柠檬来制作.
于是店员使用if语句查询是否为0:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def
make_lemonade
(
count
):
...
def
out_of_stock
():
...
count = fresh_fruit.get(
'lemon'
,
)
if
count:
make_lemonade(count)
else
:
out_of_stock()
这里的count在if前定义了一次,但它只在if的第一个代码块中使用到了,因此在if前定义显得有些多余,会分散对这个变量的注意力。现实中很多类似的情况,例如检查一个值并使用它。使用海象运算符可以简化这种情况:
1
2
3
4
5
6
7
8
9
if
count := fresh_fruit.get(
'lemon'
,
):
make_lemonade(count)
else
:
out_of_stock()
可以看到这里的count只跟if中的判断有关系,这样代码关系的清晰度就提高了。
上面是将整个海象运算符前后作为一个boolean类型来判断,而如果需要将它做运算比较,那么需要使用()将其包裹,例如:
1
2
3
4
5
6
if
(count := fresh_fruit.get(
'apple'
,
)) >=
:
还有一种情况是,频繁使用的switch/case语句,或多个if-else深度嵌套:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
count = fresh_fruit.get(
'banana'
,
)
if
count >=
:
pieces = slice_bananas(count)
to_enjoy = make_smoothies(pieces)
else
:
count = fresh_fruit.get(
'apple'
,
)
if
count >=
:
to_enjoy = make_cider(count)
else
:
count = fresh_fruit.get(
'lemon'
,
)
if
count:
to_enjoy = make_lemonade(count)
else
:
to_enjoy =
'Nothing'
海象运算符同样可以替代,作为优化版本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
count = fresh_fruit.get(
'banana'
,
)
if
count >=
:
pieces = slice_bananas(count)
to_enjoy = make_smoothies(pieces)
else
:
count = fresh_fruit.get(
'apple'
,
)
if
count >=
:
to_enjoy = make_cider(count)
else
:
count = fresh_fruit.get(
'lemon'
,
)
if
count:
to_enjoy = make_lemonade(count)
else
:
to_enjoy =
'Nothing'
“海象”运算符的语法形式为:NAME:= expr,NAME 是一个有效的标识符,而 expr 是一个有效的表达式。 因此,这意味着它不支持可迭代的打包和拆包。
当然海象运算符还有其他高阶用法(比如推导式),就不一一介绍了,反正估计也用不太上。只需要记住一点,碰到需要创建临时变量并判断时,就可以用海象运算符做优化代码的处理。
Python3.8-海象运算符
https://zhouyinglin.top/2023/04/19/Python3.8-海象运算符/